Writing to a JSON file

The initial steps are almost similar to reading from a JSON file.

Step 1: Make sure JSON library is installed.

Step 2: Import the JSON library to the code:

require ‘json’

Step 3: Create some data to write to file.

data_to_write = {

“name” => “Stephen”,

“age” => 76,

“city” => “New York”

}

Step 4: The JSON.generate method is used to convert a Ruby data structure (data_to_write) into a JSON-formatted string. The generate function takes a Ruby data structure as input and converts it into a JSON-formatted string.

json_data = JSON.generate(data_to_write)

Step 5: Write to the file using the following line of code:

file_path = ‘output.json’

File.open(file_path, ‘w’) do |file|

file.write(json_data)

end

Let’s break it down a bit:

  1. First we assign a file name to the output json file to the variable file_path.
  2. Then we use the File library in order to open a file with the given file name and write to it. This is achieved by the File.open() method which takes two arguments, first is the file name and the mode of it. Here we use ‘w’ to indicate that we need to write to the file.
  3. Inside this block we use file.write to write each line of the JSON data that is to be stored.

Code:

Ruby
require 'json'

# Create some data to be written to the JSON file
data_to_write = {
  "name" => "John",
  "age" => 30,
  "city" => "New York"
}

# Convert the data to JSON format
json_data = JSON.generate(data_to_write)

# Write the JSON data to a file
file_path = 'output.json'
File.open(file_path, 'w') do |file|
  file.write(json_data)
end

puts "Data has been written to #{file_path}"

When we run this code we will generate a new file called ‘output.json’ which will contain the contents of the variable of data_to_write.

Output:

Terminal Output

As we can see, a new file called ‘output.json’ is automatically created with the data_to_write information.

How to read/write JSON File?

Ruby is a dynamic, object-oriented programming language developed by Yukihiro Matsumoto in the mid-1990s. Its key features include a simple and elegant syntax, dynamic typing, object-oriented nature, support for mixins and modules, blocks and closures, metaprogramming, and a vibrant community with a rich ecosystem of libraries and frameworks. Ruby is popular for web development, automation scripts, and system administration tasks, and is primarily used through the Ruby on Rails web framework. It is also used for various other applications outside of web development.

Similar Reads

Reading from a JSON file

In Ruby, we can easily read and write JSON files using the built-in JSON library....

Writing to a JSON file

The initial steps are almost similar to reading from a JSON file....

FAQs

1. How can I ensure proper formatting when writing JSON data to a file?...

Contact Us