Environment configuration
Before using Ruby to encode or decode JSON data, we need to install the Ruby JSON module first. Before installing the module you need to install Ruby Gem, and we use Ruby Gem to install the JSON module. However, if you are using the latest version of Ruby, you may have a gem installed, and parsing allows us to install the Ruby JSON module using the following command:
Parsing JSON with Ruby
The following is the JSON data that 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 above JSON file;
#!/usr/bin/ruby
require ' rubygems '
require ' json '
require ' PP '
json = file.read (' Input.json ')
obj = Json.parse (JSON)
pp obj
The results of the above examples are:
{"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"]
}