Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

Ruby JSON


May 12, 2021 Ruby


Table of contents


Ruby JSON

In this section, we'll show you how to encode and decode JSON objects using the Ruby language.


Environment configuration

Before we can encode or decode JSON data with Ruby, we need to install the Ruby JSON module. Y ou need to install the Ruby gem before you install the module, and we use the Ruby gem to install the JSON module. However, if you're using the latest version of Ruby and you may already have a gem installed, we can use the following commands to install the Ruby JSON module:

$gem install json

Use Ruby to parse JSON

The following is JSON data, which 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 JSON files above;

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

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

pp obj

The above examples perform as follows:

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