在ruby中使用JSON解析的问题

时间:2013-06-03 04:28:16

标签: ruby json httparty

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插件上为我做同样的事情但是昨天工作,现在没什么。我做错了吗?

1 个答案:

答案 0 :(得分: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