1
page = HTTParty.get("https://api.4chan.org/b/0.json").body
threads = JSON.parse(page)
count = 0

unless threads.nil?
    threads['threads'].each do
      count = count + 1
    end
end


if count > 0
    say "You have #{count} new threads."
     unless threads['posts'].nil?
      threads['posts'].each do |x|
        say x['com']
      end
     end
end

if count == 0
    say "You have no new threads."
end

for some reason it says that posts is empty i guess but threads never is....I am not sure whats wrong and its doing the same thing for me on the facebook plugin but that worked yesterday and now nothing. Am I doing something wrong?

1 Answer 1

1

You need to initialize your threads variable like this:

threads = JSON.parse(page)['threads']

The root node in the JSON response you received is "threads". All of the content you want to access is contained within the array of this node.

Each thread contains many posts. So to iterate through all of the posts, you will need to do something like this:

threads.each do |thread|
  thread["posts"].each do |post|
    puts post["com"]
  end
end

Overall I would rewrite your code like so:

require 'httparty'
require 'json'

page = HTTParty.get("https://api.4chan.org/b/0.json").body
threads = JSON.parse(page)["threads"]
count = threads.count

if count > 0
  puts "You have #{count} new threads."
  threads.each do |thread|
    unless thread["posts"].nil?
      thread["posts"].each do |post|
        puts post["com"]
      end
    end
  end
else
  puts "You have no new threads."
end
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.