- JSON - 示例
- 使用 PHP 的 JSON
- 使用 Perl 的 JSON
- 使用 Python 的 JSON
- 使用 Ruby 的 JSON
- 使用 Java 的 JSON
- 使用 Ajax 的 JSON
- JSON 实用资源
- JSON - 快速指南
- JSON - 实用资源
- JSON - 讨论
使用 Ruby 的 JSON
本章介绍如何使用 Ruby 编程语言对 JSON 对象进行编码和解码。首先让我们准备环境,以便开始使用 Ruby 对 JSON 进行编程。
环境
在开始使用 Ruby 对 JSON 进行编码和解码之前,你需要安装适用于 Ruby 的任意 JSON 模块。你可能需要安装 Ruby gem,但是如果你运行的是最新版本的 Ruby,那么你的电脑上肯定已经安装了 gem,如果没有的话,让我们执行以下单个步骤,假定你已经安装了 gem −
$gem install json
使用 Ruby 解析 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"]
}
广告