如何访问json响应rails中的值? [重复]

时间:2021-01-17 16:01:35

This question already has an answer here:

这个问题在这里已有答案:

So I have installed the gem Httparty on my rails app. I test if its working on my console first so this is what I'm doing:

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

I get the response first from the url:

我首先从网址获得响应:

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

I get this value:

我得到这个值:

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

By this I can access each value doing this:

通过这个我可以访问每个值这样做:

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

So basically if you type in 'price' on the console you will get the value of 54.333011.

因此,基本上如果您在控制台上键入“价格”,您将获得54.333011的值。

Meanwhile when I do the steps above with this one:

与此同时,当我使用以下步骤执行上述步骤时:

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"
        ],

I get these bunch of data but I can't access each of the value inside when I try my steps above

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

id = hero["id"]

Traceback (most recent call last): 2: from (irb):37 1: from (irb):37:in '[]' TypeError (no implicit conversion of String into Integer)

回溯(最近一次调用最后一次):2:from(irb):37 1:from(irb):37:in'[]'TypeError(没有将String隐式转换为整数)

I get this error.

我收到这个错误。

1 个解决方案

#1


0  

response is in Array of (JSON)hashes

响应是在(JSON)哈希数组中

so, you can try this

所以,你可以试试这个

id = hero[0]["id"]

#1


0  

response is in Array of (JSON)hashes

响应是在(JSON)哈希数组中

so, you can try this

所以,你可以试试这个

id = hero[0]["id"]