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

Use JSON in Ruby


May 08, 2021 JSON


Table of contents


Use JSON in Ruby

This tutorial will teach us how to encode and decode JSON using the Ruby programming language. Let's prepare the environment for Ruby programming for JSON.

Environment

Before we can encode and decode JSON with Ruby, we need to install a JSON module that is available for Ruby. You may need to install Ruby gem, we use Ruby gem to install the JSON module, if you are using the latest version of Ruby, then you may have installed gem, install gem, please follow these steps:

$gem install json

Use Ruby to parse JSON

The following example shows the first 2 keys holding string values and the last 3 holding string arrays. Let's save the following as a file called 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"
    ]
}

Here's the Ruby program used to parse the JSON document above:

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

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

pp obj

The results are generated on execution 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"]
}