如何访问json响应轨道内的值?

时间:2018-10-04 10:12:54

标签: ruby-on-rails json

因此,我已在我的rails应用程序上安装了gem Httparty。我先测试它是否可以在我的控制台上正常工作,所以这就是我正在做的事情:

我首先从URL得到响应:

rate = HTTParty.get("https://free.currencyconverterapi.com/api/v6/convert?q=USD_PHP").parsed_response

我得到这个值:

{"query"=>{"count"=>1}, "results"=>{"USD_PHP"=>{"id"=>"USD_PHP", "val"=>54.333011, "to"=>"PHP", "fr"=>"USD"}}}

这样,我可以执行以下操作访问每个值:

price = rate["results"]["USD_PHP"]["val"]
54.333011 

因此,基本上,如果您在控制台上输入“ price”,则将获得54.333011的值。

与此同时,当我执行上述步骤时:

hero = HTTParty.get("https://api.opendota.com/api/heroes").parsed_response
 [
    {
        "id": 1,
        "name": "npc_dota_hero_antimage",
        "localized_name": "Anti-Mage",
        "primary_attr": "agi",
        "attack_type": "Melee",
        "roles": [
            "Carry",
            "Escape",
            "Nuker"
        ],
        "legs": 2
    },
    {
        "id": 2,
        "name": "npc_dota_hero_axe",
        "localized_name": "Axe",
        "primary_attr": "str",
        "attack_type": "Melee",
        "roles": [
            "Initiator",
            "Durable",
            "Disabler",
            "Jungler"
        ],
        "legs": 2
    },
    {
        "id": 3,
        "name": "npc_dota_hero_bane",
        "localized_name": "Bane",
        "primary_attr": "int",
        "attack_type": "Ranged",
        "roles": [
            "Support",
            "Disabler",
            "Nuker",
            "Durable"
        ],

我得到了这些数据,但是当我尝试上述步骤时,我无法访问其中的每个值

id = hero["id"]
  

回溯(最近通话最近):           2:来自(irb):37           1:来自(irb):37:in'[]'TypeError(不会将String隐式转换为Integer)

我收到此错误。

1 个答案:

答案 0 :(得分:0)

响应位于(JSON)哈希数组中

所以,您可以尝试

id = hero[0]["id"]