从JSON文件中提取数据

时间:2016-11-19 17:11:54

标签: json ruby hash

嘿我试图在这个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

当我运行它时,它说身体钥匙没有找到?

2 个答案:

答案 0 :(得分:0)

<!DOCTYPE html>
<html>
<body>

<h1><u> Traffic Light Sequence </u></h1>

<p>Press the button to begin.</p>

<img id="colour" src="F:\TrafficLightRed.jpg">


<button type="button" onclick="changeLights()">Change Lights</button>
<button type="button" onclick="resetLights()">Reset Lights</button>

<script>
  var timeIndex = 0;
  var lightIndex = 0;
  var timer;
  var trafficLight = document.getElementById('colour');
  var lights = [{
    duration: 2,
    image: 'F:\TrafficLightRed.jpg'
  }, {
    duration: 2,
    image: 'F:\TrafficLightRedAmber.jpg'
  }, {
    duration: 2,
    image: 'F:\TrafficLightGreen.jpg'
  }, {
    duration: 2,
    image: 'F:\TrafficLightAmber.jpg'
  }]

  function resetLights() {
    lightIndex = 0
  }

  function changeLights() {
    timeIndex++;
    if(timeIndex == lights[lightIndex].duration) {
      timeIndex = 0;
      trafficLight.src = lights[lightIndex].image;
      lightIndex = lightIndex + 1;
      if(lightIndex == 4) {
        lightIndex = 0
      }
    }
  }
  timer = setInterval(changeLights, 1000);
</script>

</body>
</html>

返回

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"=>
         "&lt;div class=\"md\"&gt;&lt;p&gt;Oh. The more you know&lt;/p&gt;\n&lt;/div&gt;",
        "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"]

答案 1 :(得分:0)

您已将json数据作为变量data_hash["data"]["children"].first["data"]["body"] rescue "" 中的哈希,来自以下代码:

data_hash

只需从此哈希变量中获取适当的数据密钥即可。您收到此错误,因为正在您正在阅读的json中,正文不在父级别。您可以通过以下代码获取此代码,这是正文密钥的确切路径:

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." 方法,因为fetch已经是哈希,所以您也可以执行以下操作:

data_hash

同样也可以访问其他数据变量。

在Ruby 2.3+中,您也可以通过以下方式完成:

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