How to read/write JSON File?
Last Updated :
02 Apr, 2024
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.
- 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.
- 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.
- 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.
- 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:
{"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:
- First we assign a file name to the output json file to the variable file_path.
- 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.
- 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 OutputAs we can see, a new file called 'output.json' is automatically created with the data_to_write information.

Similar Reads
How to Read JSON Files with Pandas?
JSON (JavaScript Object Notation) store data using key-value pairs. Reading JSON files using Pandas is simple and helpful when you're working with data in .json format. There are mainly three methods to read Json file using Pandas Some of them are:Using pd.read_json() MethodUsing JSON Module and pd.
2 min read
How to read and write JSON files in Scala?
Scala is frequently used for reading and writing JSON files in a variety of applications, particularly it includes data transmission.Table of ContentSteps for reading JSON files in Scala:Steps for writing JSON files in Scala:Steps for reading JSON files in Scala:When reading JSON files in Scala we f
3 min read
How to read and write JSON file using Node ?
Node JS is a free and versatile runtime environment that allows the execution of JavaScript code outside of web browsers. It finds extensive usage in creating APIs and microservices, catering to the needs of both small startups and large enterprises.JSON(JavaScript Object Notation) is a simple and t
3 min read
How to read JSON files in R
JSON (JavaScript Object Notation) is a lightweight data-interchange format that is easy to read for humans as well as machines to parse and generate. It's widely used for APIs, web services and data storage. A JSON structure looks like this:{ "name": "John", "age": 30, "city": "New York"}JSON data c
2 min read
How to Open JSON File?
JSON (JavaScript Object Notation) is a lightweight, text-based data format that stores and exchanges data. Let's see how we can create and open a JSON file.How to Create JSON Files?Before learning how to open a JSON file, it's important to know how to create one. Below are the basic steps to create
2 min read
How to open JSON file ?
In this article, we will open the JSON file using JavaScript. Â JSON stands for JavaScript Object Notation. It is basically a format for structuring data. The JSON format is a text-based format to represent the data in form of a JavaScript object.Approach:Create a JSON file, add data in that JSON fil
2 min read
RapidJSON - File Read/Write in C++
RapidJSON is a C++ library for parsing and generating JSON (JavaScript Object Notation) data. Â It is designed for high performance and can handle very large JSON documents. RapidJSON supports both reading and writing JSON data, as well as validation and manipulation of JSON objects. It also includes
6 min read
How to Read Large JSON file in R
First, it is important to understand that JSON (JavaScript Object Notation), is a lightweight data-interchange format that is easy for humans to read and write and easy for machines to parse and generate. JSON files are often used for data transmission between a server and a web application and can
6 min read
How to read this JSON file with jsonlite in R?
JSON data is represented as key-value pairs, which are similar to the concept of a dictionary in Python or a list of named elements in R. In this article, we will learn how to access different components of a JSON file using R. What is jsonlite package in R? The jsonlite package in R provides an eas
2 min read
How to Read and Parse Json File with RapidJson?
RapidJSON is a high-performance JSON library for C++. It provides a fast and easy-to-use interface for parsing and generating JSON. It is small but complete. It supports both SAX and DOM style API. Also, it is self-contained and header-only. It does not depend on external libraries such as BOOST. It
5 min read