2016-11-19 113 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