本節描述如何在Ruby中編碼/解碼JSON。Ruby需要外部JSON模塊來處理JSON。Ruby gem是可以安裝的推薦模塊(如果您的機器上還沒有安裝)
安裝json
讓我們看看如何使用Ruby處理JSON文件。這個例子顯示了印度男子板球隊的JSON表示。讓我們將內容存儲在cricket.json中。
{“教練”:“拉維·沙斯特裏”“隊長”:“維拉特·霍利”,“副隊長”:“羅希特·夏爾馬”,“擊球手”:[“羅希特·夏爾馬”,“維拉特·科利”,“KL·拉胡爾”,“Surya Kumar Yadav”,“Manish Pandey”],“保齡球手”:[“Jasprit Bumrah”,“Md Shami”,“Bhuvneshwar Kumar”,“Ravi Ashwin”,“Yuzi Chahal”],“全能選手”:[“Hardik Pandya”,“Ravindra Jadeja”,“Krunal Pandya”],“守門員”:[“Ishaan Kishan”,“Rishabh Pant”,]}
現在讓我們用Ruby編寫一個簡單的程序來解析cricket.json
# !/usr/bin/ruby require 'rubygems' require 'json' pp' myCricketjson = File.read('cricket.json') myCricketobj = json .parse(myCricketjson) pp myCricketobj輸出如下{"Coach"=>"Ravi Shastri", "Captain"=>"Virat Kholi", "副隊長"=>"Rohit Sharma", "Batsman"=>["Rohit Sharma", "Virat Kohli", "KL Rahul", "Surya Kumar Yadav", "Manish Pandey"], "Bowlers"=> ["Jasprit Bumrah", "Md Shami", "Bhuvneshwar Kumar", "Ravi Ashwin", "Yuzi Chahal"], "全能選手"=>[" Hardik Pandya","拉文德拉·雅德賈","克魯納爾·潘迪亞"],"守門員"=>["伊桑·基山","裏沙布·潘特"]}