Easy Tutorial
❮ Ruby Hash Ruby Iterators ❯

Ruby JSON

In this section, we will introduce how to encode and decode JSON objects using the Ruby language.


Environment Setup

Before encoding or decoding JSON data with Ruby, we need to install the Ruby JSON module. Before installing this module, you need to have Ruby gem installed. We use Ruby gem to install the JSON module. However, if you are using the latest version of Ruby, the gem might already be installed, and then we can use the following command to install the Ruby JSON module:

$ gem install json

Parsing JSON with Ruby

The following is JSON data, which is stored in the input.json file:

input.json File

{
  "President": "Alan Isaac",
  "CEO": "David Richardson",

  "India": [
    "Sachin Tendulkar",
    "Virender Sehwag",
    "Gautam Gambhir"
  ],

  "Srilanka": [
    "Lasith Malinga",
    "Angelo Mathews",
    "Kumar Sangakkara"
  ],

  "England": [
    "Alastair Cook",
    "Jonathan Trott",
    "Kevin Pietersen"
  ]
}

The following Ruby program is used to parse the above JSON file:

Example

#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'

json = File.read('input.json')
obj = JSON.parse(json)

pp obj

The result of executing the above example is:

{"President"=>"Alan Isaac",
 "CEO"=>"David Richardson",

 "India"=>
  ["Sachin Tendulkar", "Virender Sehwag", "Gautam Gambhir"],

"Srilanka"=>
  ["Lasith Malinga ", "Angelo Mathews", "Kumar Sangakkara"],

 "England"=>
  ["Alastair Cook", "Jonathan Trott", "Kevin Pietersen"]
}
❮ Ruby Hash Ruby Iterators ❯