How to Work with JSON Data in Ruby?

JSON, which stands for JavaScript Object Notation, is a format used to exchange data between different systems. It is popular because it is easy for both computers and humans to understand. This article focuses on discussing working with JSON data in Ruby.

Table of Content

  • Installing the JSON Gem
  • Parsing JSON in Ruby
  • Generating JSON in Ruby
  • JSON with Ruby on Rails
  • Conclusion

Installing the JSON Gem

Ruby comes with a built-in JSON library, but it is always a good idea to keep your JSON gem up to date. To install the latest version, run the following command in your terminal:

gem install json

After installation, your Ruby script has to include the JSON gem:

require ‘json’

Parsing JSON in Ruby

We can use Ruby’s JSON.parse function to convert JSON data into a format that Ruby can understand. When you provide a JSON string as input to this method, it will give you back a Ruby hash or array, depending on how the JSON data is organized.

Below is the Ruby program to parse JSON:

Ruby
require 'json'

json_string = '{"name": "Alice", "age": 25, "city": "London"}'
parsed_data = JSON.parse(json_string)
puts parsed_data

Output:

Parsing JSON in Ruby

We can also parse JSON from a file using the following code:

Ruby
require 'json'

file = File.read('path/to/your/json_file.json')
parsed_data = JSON.parse(file)

puts parsed_data

Generating JSON in Ruby

In Ruby, the JSON.generate method allows you to convert a Ruby hash or array into JSON format. Simply provide a Ruby hash or array as input to this method, and it will produce a JSON string as output. This makes it convenient for creating JSON data from within your Ruby code.

Example:

Ruby
require 'json'

ruby_hash = {"name" => "Bob", "age" => 30, "city" => "New York"}

json_string = JSON.generate(ruby_hash)

puts json_string

Output:

Generating JSON in Ruby

Below is the Ruby program to parse JSON and write it to a file using the following code:

Ruby
require 'json'

ruby_hash = {"name" => "Bob", "age" => 30, "city" => "New York"}
File.open('path/to/your/output_file.json', 'w') do |file|
  file.write(JSON.pretty_generate(ruby_hash))
end

JSON with Ruby on Rails

Ruby on Rails provides built-in support for JSON, allowing easy rendering of JSON responses using the render method in controllers. This means you can quickly return JSON data from your Rails application without any additional configuration. It simplifies the process of interacting with JSON data within Rails applications, making development more efficient.

Below is the program to parse JSON:

Ruby
class UsersController < ApplicationController
  def index
    @users = User.all
    render json: @users
  end
end

We can also parse JSON data from request bodies using the params method. For example, to handle a JSON payload in a POST request:

Ruby
class UsersController < ApplicationController
  def create
    @user = User.new(name: params[:name], age: params[:age], city: params[:city])

    if @user.save
      render json: @user, status: :created
    else
      render json: @user.errors, status: :unprocessable_entity
    end
  end
end

Conclusion

In this lesson, We have learned how to work with JSON in Ruby, covering parsing, generating, and integrating it with Ruby on Rails. Proficiency with JSON is crucial for Ruby developers, given its widespread use in contemporary software development.