create a json file in ruby

To create a JSON file in Ruby, you first need to create a Ruby object that can be serialized into JSON. Then, you can use Ruby's built-in json library to convert that object into a JSON string and write it to a file.

Here's an example:

main.rb
require 'json'

# Create a Ruby hash
my_data = {
  "name" => "John Smith",
  "age" => 35,
  "city" => "New York"
}

# Convert the hash to a JSON string
json_string = JSON.generate(my_data)

# Open a file for writing
File.open("my_file.json", "w") do |f|
  # Write the JSON string to the file
  f.write(json_string)
end
319 chars
18 lines

In this example, we first require the json library. Then we create a Ruby hash representing some data, and use JSON.generate to convert it to a JSON string. Finally, we use File.open to open a file for writing, and write the JSON string to the file using f.write. The resulting file, my_file.json, will contain the JSON data.

gistlibby LogSnag