我正在尝试从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>'
您正在尝试遍历data,这是一个哈希,而不是一个列表。您需要通过以下方式从JSON对象中获取children数组:data['data']['children']
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