require 'json'
file = File.read('comments.json')
data_hash=JSON.parse(file)
require 'pp'
pp data_hash
回報
{"kind"=>"Listing",
"data"=>
{"modhash"=>"",
"children"=>
[{"kind"=>"t1",
"data"=>
{"subreddit_id"=>"t5_2qlqh",
"edited"=>false,
"banned_by"=>nil,
"removal_reason"=>nil,
"link_id"=>"t3_5dq9i2",
"link_author"=>"crazyg0od33",
"likes"=>nil,
"replies"=>"",
"user_reports"=>[],
"saved"=>false,
"id"=>"da73zcw",
"gilded"=>0,
"archived"=>false,
"report_reasons"=>nil,
"author"=>"not_a_miscarriage",
"parent_id"=>"t1_da73w7s",
"score"=>1,
"approved_by"=>nil,
"over_18"=>false,
"controversiality"=>0,
"body"=>"Oh. The more you know",
"link_title"=>
"Get the Google Home speaker for $99 at Best Buy on Black Friday",
"author_flair_css_class"=>nil,
"downs"=>0,
"body_html"=>
"<div class=\"md\"><p>Oh. The more you know</p>\n</div>",
"quarantine"=>false,
"subreddit"=>"Android",
"name"=>"t1_da73zcw",
"score_hidden"=>true,
"stickied"=>false,
"created"=>1479604485.0,
"author_flair_text"=>nil,
"link_url"=>"http://blackfriday.bestbuy.com/?category=connected+home2",
"created_utc"=>1479575685.0,
"distinguished"=>nil,
"mod_reports"=>[],
"num_reports"=>nil,
"ups"=>1}}],
"after"=>"t1_da73zcw",
"before"=>nil}}
所以你要找的身體:
data_hash["data"]["children"].first["data"]["body"]
有了這麼多的哈希的請求,你可能想要寫:
data_hash["data"]["children"].first["data"]["body"] rescue ""
'data_hash.dig( '數據', '孩子',0, '數據', '體') '也可以在Ruby 2.3+中使用。 – tadman
@tadman謝謝,在答案中加入了它。 – Saurabh