Ruby - 遍历解析的 JSON
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22132623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Ruby - iterate over parsed JSON
提问by mcnollster
I'm trying to iterate of a parsed JSON response from reddit's API.
我正在尝试迭代来自 reddit 的 API 的已解析 JSON 响应。
I've done some googling and seems others have had this issue but none of the solutions seem to work for me. Ruby is treating ['data]['children] as indexes and that's causing the error but I'm just trying to grab these values from the JSON. Any advice?
我已经做了一些谷歌搜索,似乎其他人也有这个问题,但似乎没有一个解决方案对我有用。Ruby 将 ['data]['children] 视为索引,这导致了错误,但我只是想从 JSON 中获取这些值。有什么建议吗?
My code:
我的代码:
require "net/http"
require "uri"
require "json"
uri = URI.parse("http://www.reddit.com/user/brain_poop/comments/.json")
response = Net::HTTP.get_response(uri)
data = JSON.parse(response.body)
data.each do |child|
print child['data']['body']
end
The error message I get in terminal:
我在终端中收到的错误消息:
api-reddit-ruby.rb:12:in `[]': no implicit conversion of String into Integer (TypeError)
from api-reddit-ruby.rb:12:in `block in <main>'
from api-reddit-ruby.rb:11:in `each'
from api-reddit-ruby.rb:11:in `<main>'
回答by Mia Clarke
You're trying to iterate over data, which is a hash, not a list. You need to get the children array from your JSON object by data['data']['children']
您正在尝试迭代data,这是一个散列,而不是一个列表。您需要通过以下方式从 JSON 对象中获取 children 数组data['data']['children']
require "net/http"
require "uri"
require "json"
uri = URI.parse("http://www.reddit.com/user/brain_poop/comments/.json")
response = Net::HTTP.get_response(uri)
data = JSON.parse(response.body)
data['data']['children'].each do |child|
puts child['data']['body']
end

