$gem install json
使用 Ruby 解析 JSON
以下为JSON数据,将该数据存储在 input.json 文件中:
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"
]
}
以下的 Ruby 程序用于解析以上 JSON 文件;
实例
#!/usr/bin/ruby
require 'rubygems'
require 'json'
require 'pp'
json = File.read('input.json')
obj = JSON.parse(json)
pp obj
以上实例执行结果为:
{"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"]
}