Ruby JSON


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


Environment configuration

Before using Ruby to encode or decode JSON data, we need to install the Ruby JSON module first. You need to install the Ruby gem before installing this module. We use the Ruby gem to install the JSON module. However, if you are using the latest version of Ruby, you may have installed the gem. After parsing, we can use the following command to install the Ruby JSON module:

$gem install json

Use Ruby to parse JSON

The following is JSON data, which is stored in the 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;

#!/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"]
}