问题描述
我正在尝试迭代来自 reddit 的 API 的已解析 JSON 响应.
I'm trying to iterate of a parsed JSON response from reddit's API.
我做了一些谷歌搜索,似乎其他人也遇到了这个问题,但似乎没有一个解决方案对我有用.Ruby 将 ['data]['children] 视为索引,这导致了错误,但我只是想从 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?
我的代码:
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>'
推荐答案
您正在尝试迭代 data
,它是一个散列,而不是一个列表.您需要通过 data['data']['children']
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']
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
这篇关于Ruby - 遍历解析的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!