Skip to content

Parsing JSON with Ruby

Ruby, JSON, Parsing1 min read

Before delving into the specifics of parsing JSON in Ruby, it's important to understand what JSON parsing entails. Parsing JSON refers to the act of converting JSON-formatted data into a format that can be easily manipulated and utilized within a programming language, such as Ruby. This process involves extracting the structured data from a JSON string and transforming it into native data types, such as hashes and arrays in the case of Ruby.

Ruby's Built-in JSON Library

Ruby provides a built-in library called 'json' that facilitates the parsing and generation of JSON data. This library offers methods for decoding JSON data into Ruby objects and encoding Ruby objects into JSON. To work with JSON in Ruby, you can simply require the 'json' library at the beginning of your script or application.

Example 1: Decoding JSON

Let's begin by examining a simple example of decoding JSON in Ruby using the 'json' library. Assume we have a JSON file named 'data.json' containing the following:

1require 'json'
3json_data = '{"name": "John Doe", "age": 30, "city": "New York"}'
4parsed_data = JSON.parse(json_data)
6puts parsed_data['name'] # Output: John Doe
7puts parsed_data['age'] # Output: 30
8puts parsed_data['city'] # Output: New York

In this example, we use the JSON.parse method to convert the JSON-formatted string json_data into a Ruby hash named parsed_data. We then access the individual key-value pairs within the hash using their respective keys.

Example 2: Encoding to JSON

Conversely, encoding Ruby objects into JSON is also straightforward with the 'json' library. Consider the following example where we encode a Ruby hash into JSON:

1require 'json'
3person_data = { name: 'Alice', age: 25, city: 'San Francisco' }
4json_data = JSON.generate(person_data)
6puts json_data # Output: {"name":"Alice","age":25,"city":"San Francisco"}

In this example, we utilize the JSON.generate method to convert the Ruby hash person_data into a JSON-formatted string, which is then printed to the console.

Handling JSON from External Sources

When working with real-world applications, it's common to interact with external APIs that return JSON data. Ruby's 'json' library allows us to easily handle JSON received from external sources by leveraging its decoding capabilities. Here's an example of retrieving JSON data from an API and parsing it in Ruby:

1require 'net/http'
2require 'json'
4url = URI('')
5response = Net::HTTP.get(url)
6parsed_response = JSON.parse(response)
8# Process the parsed JSON data

In this example, we use the 'net/http' library to make a GET request to an API endpoint, retrieve the JSON response, and subsequently parse it using the 'json' library, making the data available for further manipulation within the Ruby application.