Open In App

How to read/write JSON File?

Last Updated : 02 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Reading from a JSON file

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

Step 1: Make sure you have the JSON library installed. In case it is not, use the following command to install JSON:

gem install json

Step 2: Import the JSON library using the following command:

require ‘json’

Step 3: Read the file using the following command:

json_data = File.read(‘data.json’)

We’re using Ruby’s built-in File class to read the contents of a file. It reads the contents of the file specified and returns it as a string. In the context of JSON files, this line of code is typically used to read the JSON data from a file into a variable (json_data in this case), so that you can then parse and work with the JSON data in your Ruby program.

Step 4: Parse the given file into hash using the following line of code:

parsed_data = JSON.parse(json_data)

In this line we’re using the JSON.parse method to convert a JSON-formatted string (json_data) into a Ruby data structure.

  1. JSON: This is the module provided by the json library that we required earlier using require ‘json’. This module contains methods for working with JSON data in Ruby.
  2. parse: It takes a JSON-formatted string as input and converts it into an equivalent Ruby data structure. The resulting Ruby data structure could be a hash, an array, a string, a number, or nil, depending on the contents of the JSON string.
  3. json_data: This is the JSON-formatted string that we want to parse. It contains data encoded in the JSON format, which could have been read from a file, received from an API, or obtained from any other source.
  4. parsed_data: This is the variable where we’re storing the result of parsing the JSON data. After this line executes, parsed_data will hold a Ruby data structure representing the JSON data. You can then access and manipulate this data using Ruby’s built-in methods and constructs. For example, if the JSON data represents an object, parsed_data will be a hash in Ruby, allowing you to access its keys and values like any other hash.

Step 5: The inpect method is used to get a string representation stored in the variable ‘parsed_data’:

puts parsed_data.inspect

Code:

Ruby
require 'json'

# Open and read the JSON file
file_path = 'data.json'
json_data = File.read(file_path)

# Parse the JSON data
parsed_data = JSON.parse(json_data)

# Now you can work with the parsed data
puts parsed_data.inspect

data.json:

{

“author”:”Stephen Hawking”,

“url”:”https://penguinrandomhouse.com/the-read-down/stephen-hawking/”,

“books”:

{

“1”:”A Brief History of Time”,

“2”:”The Grand Design”,

“3”: “How to Make a Spaceship”

}

}

Output:

Screenshot-2024-03-20-095432

{“author”=>”Stephen Hawking”, “url”=>”https://penguinrandomhouse.com/the-read-down/stephen-hawking/”, “books”=>{“1″=>”A Brief History of Time”, “2”=>”The Grand Design”, “3”=>”How to Make a Spaceship”}}

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:

Screenshot-2024-03-20-095703

Terminal Output

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

Screenshot-2024-03-20-095757

FAQs

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

Ruby’s JSON.generate method typically produces properly formatted JSON output. However, you can specify options for indentation and other formatting preferences to ensure the output meets your requirements.

2. Can I append JSON data to an existing file in Ruby?

Yes, you can append JSON data to an existing file in Ruby by opening the file in append mode (‘a’) using Ruby’s File class, and then writing the JSON data to the file. However, you need to ensure that the data you append is properly formatted JSON.

3. How can I handle errors when reading JSON data from a file in Ruby?

When reading JSON data from a file in Ruby, you should be prepared to handle potential errors, such as invalid JSON syntax or missing files. You can use error handling mechanisms like begin-rescue blocks to gracefully handle such situations.

4. What should I do if the JSON data in the file is too large to fit into memory?

If the JSON data in the file is too large to fit into memory all at once, you can process it incrementally or in chunks to avoid loading the entire file into memory.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads