Latest web development tutorials

Ruby JSON

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


Environment Configuration

Before using Ruby JSON encoding or decoding data, we need to first install Ruby JSON module. Before installing the module you need to install the Ruby gem, we use Ruby gem install JSON module. However, if you are using the latest version of Ruby, might have installed gem, we will be able to resolve to install Ruby JSON module, use the following command:

$gem install json

Use Ruby parsing JSON

Here is the JSON data, the data is stored in 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 to parse JSON over document;

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

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

pp obj

The above examples Implementation of the results:

{"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"]
}