JSON

JSON with Ruby

JSON with Ruby

This section describes how to encode/decode JSON in Ruby. Ruby requires external JSON module to process JSON. Ruby gem is the recommended module that can be installed (if not already installed on your machine)

$gem install json

Let us see how to process a JSON file using Ruby. This example shows JSON presentation of Indian Men's cricket team. Let store the contents in cricket.json.

{
    "Coach": "Ravi Shastri"
	"Captain": "Virat Kholi",
    "Vice Captain": "Rohit Sharma",
  
   "Batsman": [
      "Rohit Sharma",
      "Virat Kohli",
      "KL Rahul",
	  "Surya Kumar Yadav",
	  "Manish Pandey"
   ],

   "Bowlers": [
      "Jasprit Bumrah",
      "Md Shami",
	  "Bhuvneshwar Kumar",
      "Ravi Ashwin",
	  "Yuzi Chahal"
   ],

   "Allrounders": [
      "Hardik Pandya",
      "Ravindra Jadeja",
      "Krunal Pandya"
   ],
   
   "Wicket Keepers": [
      "Ishaan Kishan",
      "Rishabh Pant",
   ]	
}

Now let us write a simple program in Ruby to parse cricket.json

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

myCricketjson = File.read('cricket.json')
myCricketobj = JSON.parse(myCricketjson)

pp myCricketobj

The output will be as follows
{
   "Coach"=>"Ravi Shastri",
   "Captain"=>"Virat Kholi",
   "Vice Captain"=>"Rohit Sharma",

   "Batsman"=>["Rohit Sharma", "Virat Kohli", "KL Rahul", "Surya Kumar Yadav", "Manish Pandey"],

   "Bowlers"=>
   ["Jasprit Bumrah", "Md Shami", "Bhuvneshwar Kumar", "Ravi Ashwin", "Yuzi Chahal"],

   "Allrounders"=>
   ["Hardik Pandya", "Ravindra Jadeja", "Krunal Pandya"],

   "Wicket Keepers"=>
   ["Ishaan Kishan", "Rishabh Pant"]  
}