使用Ruby來處理JSON的簡單教程_ruby專題

來源:互聯網
上載者:User

環境配置

在使用 Ruby 編碼或解碼 JSON 資料前,我們需要先安裝 Ruby JSON 模組。在安裝該模組前你需要先安裝 Ruby gem,我們使用 Ruby gem 安裝 JSON 模組。 但是,如果你使用的是最新版本的 Ruby,可能已經安裝了 gem,解析來我們就可以使用以下命令來安裝Ruby JSON 模組:

$gem install json

使用 Ruby 解析 JSON

以下為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/rubyrequire '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"]}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.