红宝石 - 迭代解析的JSON [英] Ruby - iterate over parsed JSON

查看:178
本文介绍了红宝石 - 迭代解析的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图从迭代reddit的的API已解析JSON响应。

我做了一些谷歌上搜索,似乎其他人有这个问题,但没有解决方案似乎为我工作。红宝石治疗['数据] ['儿童]作为指标,这是造成错误,但我只是想从JSON抓住这些值。有什么建议?

我的code:

 要求净/ HTTP
要求URI
要求JSONURI = URI.parse(http://www.reddit.com/user/brain_poop/comments/.json)响应=净:: HTTP.get_response(URI)数据= JSON.parse(response.body)data.each做|孩子|
    打印子['数据'] ['身体']
结束

该错误消息我在终点站下车:

  API-reddit的-ruby.rb:12:`[]':字符串中的隐式转换成整数(类型错误)
从API-reddit的-ruby.rb:12:`块<主>'
从API-reddit的-ruby.rb:11:'各'
从API-reddit的-ruby.rb:11:`<主>'


解决方案

您正试图遍历 数据,这是一个哈希,而不是一个列表。您需要通过数据,从您的JSON对象children数组['数据'] ['孩子']

 要求净/ HTTP
要求URI
要求JSONURI = URI.parse(http://www.reddit.com/user/brain_poop/comments/.json)响应=净:: HTTP.get_response(URI)数据= JSON.parse(response.body)
数据['数据'] ['孩子']每做|。孩子|
    把孩子['数据'] ['身体']
结束

I'm trying to iterate of a parsed JSON response from reddit's API.

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?

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>'

解决方案

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

这篇关于红宝石 - 迭代解析的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆