Ruby JSON
本章節我們將為大家介紹如何使用 Ruby 語言來編碼和解碼 JSON 對象。
環境配置
在使用 Ruby 編碼或解碼 JSON 數據前,我們需要先安裝 Ruby JSON 模組。在安裝該模組前你需要先安裝 Ruby gem,我們使用 Ruby gem 安裝 JSON 模組。 但是,如果你使用的是最新版本的 Ruby,可能已經安裝了 gem,解析來我們就可以使用以下命令來安裝Ruby JSON 模組:
$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"] }