A simple tutorial on JSON Processing Using Ruby, and a json tutorial on ruby Processing
Environment Configuration
Before using Ruby to encode or decode JSON data, we need to install the Ruby JSON module. Before installing this module, you must first install Ruby gem. We will use Ruby gem to install the JSON module. However, if you are using the latest Ruby version, you may have installed the gem. After parsing, you can use the following command to install the Ruby JSON module:
$gem install json
Parse JSON using Ruby
JSON data 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 programs are used to parse the preceding JSON files;
#!/usr/bin/rubyrequire 'rubygems'require 'json'require 'pp' json = File.read('input.json')obj = JSON.parse(json) pp obj
The execution result of the above instance 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"]}