gpt4 book ai didi

json - 从 JSON 文件中提取数据

转载 作者:太空宇宙 更新时间:2023-11-03 16:43:05 25 4
gpt4 key购买 nike

嘿,我正在尝试在此 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

当我运行它时它说找不到正文 key ?

最佳答案

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}}

所以你要找的 body 是:

data_hash["data"]["children"].first["data"]["body"]

有这么多哈希请求,你可能想写:

data_hash["data"]["children"].first["data"]["body"] rescue ""

关于json - 从 JSON 文件中提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40695672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com