Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/21.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何迭代并从带有数组的散列中检索值?_Ruby_Json_Api - Fatal编程技术网

Ruby 如何迭代并从带有数组的散列中检索值?

Ruby 如何迭代并从带有数组的散列中检索值?,ruby,json,api,Ruby,Json,Api,我正在尝试建立一个快速的黑客程序,“喜欢”instagram上某个特定标签的所有最新照片 我已经验证并使用JSON gem将JSON从API转换为Ruby哈希,如下所示: def get_content (tag_name) uri = URI.parse("https://api.instagram.com/v1/tags/#{tag_name}/media/recent? access_token=#{@api_token}") http = Net::HTTP.new(ur

我正在尝试建立一个快速的黑客程序,“喜欢”instagram上某个特定标签的所有最新照片

我已经验证并使用JSON gem将JSON从API转换为Ruby哈希,如下所示:

def get_content (tag_name)

   uri = URI.parse("https://api.instagram.com/v1/tags/#{tag_name}/media/recent? access_token=#{@api_token}")

   http = Net::HTTP.new(uri.host, uri.port)
   http.use_ssl = true
   http.verify_mode = OpenSSL::SSL::VERIFY_NONE

   request = Net::HTTP::Get.new(uri.request_uri)

   json_output = http.request(request)
   @tags = JSON.parse(json_output.body)

end
这将输出一个散列,其中数组作为与原始JSON类似的嵌套键(例如
http://instagr.am/developer/endpoints/tags/

我正在尝试迭代并检索照片的所有“id”

但是,当我使用每种方法时:

@tags.each do |item| 
  puts item["id"]
end
我得到一个错误:

instagram.rb:23:in `[]': can't convert String into Integer (TypeError)
from instagram.rb:23:in `block in like_content'
from instagram.rb:22:in `each'
from instagram.rb:22:in `like_content'
from instagram.rb:42:in `<main>'
instagram.rb:23:in`[]:无法将字符串转换为整数(TypeError)
摘自instagram.rb:23:in'block in like_content'
来自instagram.rb:22:in'each'
来自instagram.rb:22:in'like_content'
来自instagram.rb:42:in`'

instagram.rb:23:in`[]:无法将字符串转换为整数(TypeError)
出现此错误是因为在
放置项[“id”]
中,
是一个数组,而不是散列,因此Ruby尝试将放置在
[]
之间的内容转换为整数索引,但它不能,因为它是一个字符串(
“id”

这是因为
json_output.body
是一个散列。再看一下文档中的JSON响应示例:

{“数据”:[
{“类型”:“图像”,
// ...
“id”:“22699663”,
“位置”:空
},
// ...
]
}
整个结构变成一个带有一个键的单个散列,
“data”
,因此当您调用
@标记时。每个
实际上调用的是
散列#每个
,并且由于
“data”
的值是一个数组,当您调用
项[“id”]
时,您调用的
数组#[]

长话短说,你实际上想做的可能是:

@tags=JSON.parse(JSON_output.body)[“data”]
..然后,
@tags
将是您想要的数组,而不是散列,您可以像您想要的那样迭代其成员:

@tags.each do| item|
放置项目[“id”]
结束

您确定数据是您认为的数据吗?看起来您可能对不正确的类型做出了假设。请尝试
p@tags.class、@tags
了解有关
@tags
的详细信息。解释得很好。非常感谢。解决了我的目的。