How To Read Json File In Ruby

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. It has become a popular format for web-based APIs to exchange data between client and server. In this blog post, we will learn how to read a JSON file in Ruby and work with the data.

Prerequisites

Before we begin, make sure you have Ruby installed on your system. You can check if it is installed by running the following command in your terminal:

ruby -v

If you don’t have Ruby installed, you can download and install it from the official Ruby website.

Reading a JSON File in Ruby

In order to work with JSON files in Ruby, we will use the built-in json library. First, let’s create a sample JSON file named data.json with the following content:

{
  "name": "John Doe",
  "age": 30,
  "address": {
    "street": "123 Main St",
    "city": "Anytown",
    "state": "CA",
    "zip": "12345"
  }
}

Next, create a Ruby script named read_json.rb. At the beginning of the script, we need to require the json library:

require 'json'

Now, we can read the JSON file and store its content in a variable:

file = File.read('data.json')
data = JSON.parse(file)

In the code above, we first read the file using File.read method and store the content in the file variable. Then, we use the JSON.parse method to convert the JSON content into a Ruby hash, which we store in the data variable.

To access the data, we can simply use hash keys as follows:

puts "Name: #{data['name']}"
puts "Age: #{data['age']}"
puts "Street: #{data['address']['street']}"
puts "City: #{data['address']['city']}"
puts "State: #{data['address']['state']}"
puts "Zip: #{data['address']['zip']}"

This will output the following in the terminal:

Name: John Doe
Age: 30
Street: 123 Main St
City: Anytown
State: CA
Zip: 12345

Conclusion

In this blog post, we learned how to read a JSON file in Ruby using the built-in json library. We also learned how to parse the JSON content and access the data using hash keys. This simple process can be used to read and work with JSON data from files or APIs in your Ruby projects.