Ruby - iterate over parsed JSON

mcnollster picture mcnollster · Mar 2, 2014 · Viewed 40.1k times · Source

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

Answer

Mia Clarke picture Mia Clarke · Mar 2, 2014

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