我试图像这样解析json,我得到一个错误,说key是一个字符串而不是hash。我正在尝试提取位置,名称,ID,团队的数据,并按位置类型将其推送到ruby哈希。
require 'json'
json = JSON.parse(response.body)
json.each do |key, value|
if(key =~ /players/)
key.each do |k, v|
puts k.inspect
end
end
end
{
"version": "1.0",
"players": {
"timestamp": "-1",
"player": [
{
"position": "TMDL",
"name": "Bills, Buffalo",
"id": "0251",
"team": "BUF"
},
{
"position": "TMDL",
"name": "Colts, Indianapolis",
"id": "0252",
"team": "IND"
},
{
"position": "TMDL",
"name": "Dolphins, Miami",
"id": "0253",
"team": "MIA"
}
]
}
}
答案 0 :(得分:1)
由于players
是唯一键,因此您可以使用json["players"]
直接访问它。我想你正在寻找这样的东西:
require 'json'
json = JSON.parse(response.body)
json["players"]["player"].each do |player|
puts "Player team is #{player['name']} and position is #{player['position']}"
end
答案 1 :(得分:1)
json变量已经是一个哈希(在解析之后),你可以像普通的ruby哈希一样使用它。
答案 2 :(得分:1)
也许你可以尝试这个:
require 'json'
require 'ostruct'
require 'awesome_print'
test = '{
"version": "1.0",
"players": {
"timestamp": "-1",
"player": [
{
"position": "TMDL",
"name": "Bills, Buffalo",
"id": "0251",
"team": "BUF"
},
{
"position": "TMDL",
"name": "Colts, Indianapolis",
"id": "0252",
"team": "IND"
},
{
"position": "TMDL",
"name": "Dolphins, Miami",
"id": "0253",
"team": "MIA"
}
]
}
}'
json = JSON.parse(test)
json.each do |key, value|
if(key =~ /players/)
value['player'].each do |k, v|
puts k.inspect
end
end
end