2016-11-19 150 views
2

嘿,我想在這個JSON文件打印註釋:從JSON中提取數據文件

# https://www.reddit.com/r/android/comments.json?limit=1 

    require 'json' 

    file = File.read('comments.json') 
    data_hash=JSON.parse(file) 
    comment = data_hash.fetch("body") 
    print comment 

當我運行這一點,說身體關鍵是沒有發現?

回答

0
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 "" 
0

你已經有json數據作爲vari中的散列data_hash來自以下代碼:

data_hash=JSON.parse(file) 

這只是從該散列變量中獲取適當數據密鑰的問題。

>comment = data_hash.fetch("data").fetch("children")[0].fetch("data").fetch("body") 

=> "This isn't price match, but price protection via a credit card. They'd issue a check for the difference." 

你沒必要必要:您收到此錯誤,因爲身體是不是在您正在閱讀的JSON父級別,您可以通過下面的代碼,這是身體的關鍵的確切路徑得到這個這裏使用fetch方法,如data_hash已經是亂碼,所以你可以根本就以下還有:

> data_hash["data"]["children"][0]["data"]["body"] 
=> "This isn't price match, but price protection via a credit card. They'd issue a check for the difference." 

,類似其他數據變量也可以訪問。


在Ruby 2.3及更高版本,你也可以做到這一點,只需有:

data_hash.dig('data', 'children', 0, 'data', 'body') 
+0

'data_hash.dig( '數據', '孩子',0, '數據', '體') '也可以在Ruby 2.3+中使用。 – tadman

+1

@tadman謝謝,在答案中加入了它。 – Saurabh