我正在尝试从reddit的API迭代解析的JSON响应。
我做了一些谷歌搜索,似乎其他人有这个问题,但没有一个解决方案似乎适合我。 Ruby将['data] ['children]视为索引并导致错误,但我只是试图从JSON中获取这些值。有什么建议吗?
我的代码:
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
我在终端收到的错误消息:
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>'
答案 0 :(得分:32)
你试图迭代data
,这是一个哈希,而不是一个列表。您需要通过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