English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Ruby JSON

In this chapter, we will introduce how to encode and decode JSON objects using the Ruby language.

Environment Configuration

Before using Ruby to encode or decode JSON data, we need to install the Ruby JSON module first. Before installing this 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 already installed the gem, and we can use the following command to install the Ruby JSON module:

$gem install json

Using Ruby to parse JSON

The following 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;

Online Examples

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

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