Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Ruby JSON

Ruby JSON

In this chapter we will introduce 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 Ruby JSON module. Before installing this module you need to install Ruby gem first; we use Ruby gem to install the JSON module. However, if you are using the latest version of Ruby, gem may already be installed, and then we can use the following command to install the Ruby JSON module:


$gem install json

Parsing JSON with Ruby

The following is JSON data; store this data 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/ruby

require

'

rubygems

'

require

'

json

'

require

'

pp

'

json

=

File

.

read

(

'

input.json

'

)

obj

=

JSON

.

parse

(

json

)

pp

obj

The example above produces:


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