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プラグインで同じことをしていますが、昨日はうまくいきましたが、今は何もありません. 私は何か間違ったことをしていますか?

4

1 に答える 1

1

threads次のように変数を初期化する必要があります。

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

受け取った JSON 応答のルート ノードは「threads」です。アクセスするすべてのコンテンツは、このノードの配列内に含まれています。

それぞれ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
于 2013-06-03T04:48:10.767 に答える