简体   繁体   English

从Rails中的外部API遍历JSON数据

[英]Iterating through JSON data from external API in Rails

I have a function return_summoner_champion_list(name) that will return the following JSON data when called 我有一个函数return_summoner_champion_list(name) ,该函数在调用时将返回以下JSON数据

[
  {
    "id"=>"1",
    "name"=>"A"
  },
  {
    "id"=>"2",
    "name"=>"B"
  },
  and so on...
]

How do I iterate through the JSON array and print out all ids? 如何遍历JSON数组并打印所有ID?

I tried 我试过了

return_summoner_champion_list(name).each do |list|
  puts list["id"]
end

but it still returns the same JSON data as above without any changes. 但它仍返回与上述相同的JSON数据,而没有任何更改。

I think you're looking for Array#collect not Array#each : 我认为您在寻找Array#collect而不是Array#each

return_summoner_champion_list(name).collect{|l| l['id']}
=> [1,2, ...]

Is your method returning JSON or an Ruby array? 您的方法返回JSON还是Ruby数组? If it is indeed returning JSON, first convert that to an array with JSON.parse() , and then work with the array that is returned. 如果确实返回JSON,请首先使用JSON.parse()将其转换为数组,然后使用返回的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM