logo

JSON With Ruby


Show

This chapter covers the way to encode and decode JSON objects using the Ruby programming language. Let's begin with preparing the environment to begin our programming with Ruby for JSON.

Environment

Before you begin with encoding and decoding JSON the use of Ruby, you want to install any of the JSON modules available for Ruby. You may also need to install Ruby gem, but if you are running the latest model of Ruby then you definitely have the gem already installed on your machine, otherwise, let's follow the subsequent single step assuming you already have gem installed:

$gem install json

Parsing JSON using Ruby

The below given example represents that the initial 2 keys hold string values and the end 3 keys hold arrays of strings. Let's keep the following content in a file known as input.json.

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

Given under is a Ruby program in order to be used to parse the above-mentioned JSON document −

#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'

json = File.read('input.json')
obj = JSON.parse(json)

pp obj

On applying, you will get the below-given result:

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