【问题标题】:How can I access the values inside a json response rails? [duplicate]如何访问 json 响应导轨中的值? [复制]
【发布时间】:2018-10-04 19:52:53
【问题描述】:

所以我在我的 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 

所以基本上,如果您在控制台上输入“价格”,您将获得 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"]

Traceback(最近一次调用最后一次): 2:来自(irb):37 1: from (irb):37:in '[]' TypeError(没有将String隐式转换为Integer)

我收到此错误。

【问题讨论】:

  • hero 变量是一个数组。
  • 一开始它总是一个数组。你是对的,谢谢!

标签: ruby-on-rails json


【解决方案1】:

响应在 (JSON) 哈希数组中

所以,你可以试试这个

id = hero[0]["id"]

【讨论】:

  • 这确实有效,我忘记了数组是什么。傻我!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-16
  • 2013-02-03
  • 1970-01-01
  • 2022-11-14
  • 2021-08-26
  • 1970-01-01
相关资源
最近更新 更多