解析来我们就可以使用以下命令来安装Ruby JSON 模块:
1
|
$gem
install
json
|
使用 Ruby 解析 JSON
以下为JSON数据,将该数据存储在 input.json 文件中:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
{
"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 文件;
1
2
3
4
5
6
7
8
9
|
#!/usr/bin/ruby
require
'rubygems'
require
'json'
require
'pp'
json =
File
.read(
'input.json'
)
obj =
JSON
.parse(json) 转为hash 这里的json是字符串不是json对象
pp obj
|
以上实例执行结果为:
1
2
3
4
5
6
7
8
9
10
11
12
|
{
"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"
]
}
|