所以我在我的rails应用程序上安装了gem Httparty。我首先测试它是否在我的控制台上工作,所以这就是我正在做的事情:
我首先从网址得到响应:
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"]
回溯(最近一次调用(: 2: 来自 (IRB(:37 1:from (irb(:37:in '[]' TypeError (没有将字符串隐式转换为整数(
我收到此错误。
响应在 (JSON( 哈希数组中
所以,你可以试试这个
id = hero[0]["id"]