Ruby JSON

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