A simple tutorial on using Ruby to process JSON _ruby topics

Source: Internet
Author: User

Environment configuration

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

$gem Install JSON

Parsing JSON with Ruby

The following is the JSON data that 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 above JSON file;

#!/usr/bin/ruby
require ' rubygems '
require ' json '
require ' PP '
 
json = file.read (' Input.json ')
obj = Json.parse (JSON)
 
pp obj

The results of the above examples are:

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.