home PYTHONJAVA
 

Ruby JSON

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


Environment configuration

Before you can use 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, and 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;

Instance

#!/usr/bin/ruby require 'rubygems' require 'json' require 'pp' json= File.read('input.json') obj = JSON.parse(json) pp obj

The above example execution result 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"]
}





welookups is optimized for learning.© welookups. 2018 - 2019 All Right Reserved and you agree to have read and accepted our term and condition.