2013-06-03 89 views
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 

由于某种原因,它说帖子是空的我猜想,但线程从来没有....我不知道什么是错的,它在facebook插件上做同样的事情,但我昨天工作,现在什么都没有。难道我做错了什么?JSON解析红宝石问题

回答

1

需要初始化你threads变量是这样的:

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

在JSON响应您收到的根节点是“线程”。您要访问的所有内容均包含在此节点的阵列中。

每个thread包含许多posts。所以,在所有的职位进行迭代,你需要做这样的事情:

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

总的来说,我会重写,像这样的代码:

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 
+0

谢谢!这工作 – user2446537