write to a json file in ruby

You can write to a JSON file in Ruby using the built-in json library and the File class. Here's an example:

main.rb
require 'json'

# Define the data to be stored in the JSON file
data = {
  "name" => "John",
  "age" => 30,
  "city" => "New York"
}

# Convert the data to a JSON string
json_data = JSON.generate(data)

# Write the JSON string to a file
File.open('data.json', 'w') do |file|
  file.write(json_data)
end
303 chars
17 lines

In this example, we first require the json library. We then define the data that we want to store in the JSON file as a hash.

Next, we use the JSON.generate method to convert the hash to a JSON-formatted string.

Finally, we create a new file called data.json using the File.open method with the mode set to 'w', which means that we're opening the file for writing. We then write the JSON string to the file using the File.write method.

After running this code, a new file called data.json will be created in the current directory with the following contents:

{"name":"John","age":30,"city":"New York"}
43 chars
2 lines

gistlibby LogSnag