1

我正在尝试像这样解析下面的 json,但我收到一条错误消息,说 key 是 string 而不是 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"
          }
         ]
      }
   }
4

3 回答 3

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
于 2013-04-03T05:22:24.590 回答
1

json 变量已经是一个散列(解析后),你可以像普通的 ruby​​ 散列一样使用它。

于 2013-04-03T05:35:40.250 回答
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
于 2013-04-03T05:42:28.907 回答