Ruby JSON

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


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 install Ruby gem. We use Ruby gem to install the JSON module. However, if you are using the latest version of Ruby, gem may already be installed. Next, we can use the following command to install the Ruby JSON module:

$gem install json

Using Ruby to Parse JSON

The following is JSON data; store this data 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 execution result of 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"]
}
Other Extensions