JavaScript Object Notation, or JSON for short, is a simple and incredibly lightweight data exchange format. JSON is easy to write and read both for machines and humans.

JSON is everywhere, and it is used to transfer structured data over the network with a major application in APIs.

This quick guide will go over how to use and parse JSON data using the Ruby programming language.

What Is Parsing?

Parsing is the process of breaking down a component, such as a data string, into various standalone components that are usable individually.

How to Get JSON Data

Before we discuss how to parse JSON in Ruby, it is good to ensure we have a JSON file with which to work on.

If you do not have a JSON file to work with, you can use the online JSON generators or queries from a popular public API.

Installation

To parse JSON with Ruby, we need to install the JSON package using the gem package manager. We can do that using the command:

To check if the installation is successful, open IRB and run the code:

Running this command should return true if you have the package installed successfully:

irb(main):001:0> require ‘json’

=> true

How to Read the JSON File

The next step is to read the JSON data. For this, we use the File.read method, as shown in the example code below:

require ‘json’

raw_data = File.read(‘NASA.json’)

Replace the NASA.json file with the actual file name of the JSON file you wish to parse.

How to Parse JSON Data

Once we have the file loaded, we can parse the JSON data using the JSON.parse method. This method will create a Ruby hash with the JSON keys.

For example:

require ‘json’

raw_data = File.read(‘NASA.json’)

nasa_datahash = JSON.parse(raw_data)

Once loaded, we can proceed to work with the data like an ordinary Ruby hash.

For example, to get the keys, we can do:

require ‘json’

raw_data = File.read(‘NASA.json’)

nasa_datahash = JSON.parse(raw_data)

puts nasa_datahash.keys

You can also get the values stored in the JSON data using the .values method.

Write to JSON

Suppose we want to write to a json file. We start by reading the JSON file and creating a Ruby Hash. After that, we can modify the values and then write them to a JSON file.

Let’s take an example JSON file with the values as shown:

{

    “name”: “John Doe”,

    “age”: 30,

    “role”: “Python Programmer”,

    “group”: “AX-100”

}

We can start by reading the file as:

require ‘json’

file = File.read(“user.json)

Once we have the file loaded, we can parse the JSON information using the JSON.parse method as:

user_info = JSON.parse(file);

Once we have the file parsed into a Ruby Hash, we can use built-in methods to manipulate the values.

Let us start by fetching the keys:

This should print the hash keys which are basically the JSON keys. Each value is mapped to its respective value.

$ ruby json.rb

name

age

role

group

The next step is to add modifications to the existing key. We can simply use the merge method as:

user_info.merge!(“Country”: “United States”)

Once you have made all the changes to the Ruby hash and wish to write the changes back to the JSON file, we can use the write method and dump the contents of the hash in JSON format as shown in the code below.

File.write(“user.json”, JSON.dump(user_info))

Once completed, the changes will be appended to the specified file.

{

    “name”: “John Doe”,

    “age”: 30,

    “role”: “Python Programmer”,

    “group”: “AX-100”,

    “Country”: “United States”

}

Converting Hash to JSON

If you have a raw Ruby hash, you can generate JSON data using the generate method. Consider the example below:

require ‘json’

this_hash = {:name => “John Doe”, :age => 30, :role => “Python Programmer”, :group => “AX-100”, :Country => “United States”}

jsonified = JSON.generate(this_hash)

puts jsonified

The above should create JSON data with the keys and values corresponding to the keys and values of the hash.

To learn more about how to work with Ruby Hashes, consider our tutorial on the topic.

Conclusion

As shown in this tutorial, parsing JSON data is incredibly simple in Ruby. Consider the documentation to learn more.

About the author

<img alt="" data-del="avatar" data-lazy-src="https://kirelos.com/wp-content/uploads/2021/08/echo/john-150×150.png61213d506efa7.jpg" height="112" src="data:image/svg xml,” width=”112″>

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list