首页 > 解决方案 > Ruby - 使用 .dig 查询嵌套哈希中的值 - 返回空白

问题描述

我正在尝试从 reddit.com/r/programming 中提取评论并在终端中输出评论。我从 reddit 中提取 json,然后将其解析为嵌套哈希,但在查询哈希以提取评论时遇到问题。使用 HASH.dig 是正确的方法吗?

require 'net/http'
require 'rubygems'
require 'json'

url = 'https://www.reddit.com/r/programming/comments.json?sort=top&t=all&limit=10'
uri = URI(url)
response = Net::HTTP.get(uri)
json = JSON.parse(response)
puts json.dig("children","data","body")

我正在逐一查看输出评论,但是当我运行上述内容时,输出为空白。这是哈希的示例:

{"kind"=>"Listing", "data"=>{"modhash"=>"", "dist"=>10, "children"=>[{"kind"=>"t1", "data"=>{"subreddit_id"=>"t5_2tbbg", "approved_at_utc"=>nil, "edited"=>false, "mod_reason_by"=>nil, "banned_by"=>nil, "author_flair_type"=>"text", "removal_reason"=>nil, "link_id"=>"t3_8jwhvk", "author_flair_template_id"=>nil, "likes"=>nil, "replies"=>"", "user_reports"=>[], "saved"=>false, "id"=>"dz3b25e", "banned_at_utc"=>nil, "mod_reason_title"=>nil, "gilded"=>0, "archived"=>false, "report_reasons"=>nil, "author"=>"QueenCrownDown", "num_comments"=>1, "can_mod_post"=>false, "send_replies"=>true, "parent_id"=>"t3_8jwhvk", "score"=>1, "approved_by"=>nil, "over_18"=>false, "mod_note"=>nil, "collapsed"=>false, "body"=>"Any 25$ purchase or just Sunday Riley?! Def taking advantage of this I’ve wanted to try good genes for ages. ", "link_title"=>"[misc] Sunday Riley good genes 7 day sample with a $25 purchase at Sephora. Code:GOODGOOD",

标签: ruby

解决方案


推荐阅读