2013-06-03 94 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