Ruby JSON
In this section we will show you how to use the Ruby language to encode and decode JSON objects.
Environment configuration
Before using Ruby to encode or decode JSON data, we need to install the RubyJSON module. You need to install Ruby gem before installing this module, and we use Ruby gem to install the JSON module. However, if you are using the latest version of Ruby, you may have already installed gem
after parsing, we can install the Ruby JSON module using the following command
$gem install json
Parsing JSON using Ruby
Here is the 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/rubyrequire'rubygems'require'json'require'pp'json=File.read('input.json')obj=JSON.parse(json)ppobj
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"]
}