[{"ure"=>"zip*less", "prs"=>[{"mw"=>"ˈzip-ləs", "sou-6ren">
gpt4 book ai didi

json - Rubyist 测试数组中散列键的方法

转载 作者:行者123 更新时间:2023-12-04 09:25:44 25 4
gpt4 key购买 nike

我正在解析一些已转换为 Ruby 数据结构的 JSON。我有看起来像这样的记录:"uros"=>[{"ure"=>"zip*less", "prs"=>[{"mw"=>"ˈzip-ləs", "sound"=>{"audio"=>"ziples01", "ref"=>"c", "stat"=>"1"}}]或者像这样:"uros"=>[{"ure"=>"gas chromatographic", "fl"=>"adjective"}]我想提取 key audio 的哈希值当它出现时。
在 Ruby 中测试所述 key 是否存在的干净方法是什么?这是我迄今为止的尝试。变量 entry表示封闭的数据结构:

if entry["uros"] != nil # Nope              
#if entry["uros"]["prs"] != nil # Nope
#if not entry["uros"]["prs"]["sound"]["audio"].first.instance_of? nil # Nope
#if ! entry["uros"]["prs"].instance_of? nil # Nope

puts entry["uros"].first["prs"].first["sound"]["audio"]

end
我得到的错误消息是:
undefined method `first' for nil:NilClass (NoMethodError)
或者相反:
 undefined method `[]' for nil:NilClass (NoMethodError)
你会怎么做?

最佳答案

哈希有一个 method用于检查键值对的存在

if entry.key?('uros')
但是你的代码的问题是你没有检查嵌套键的存在。您检查“uros”,但“prs”可能不存在。
这是一个更好的版本,每一步都允许 nils
audio = entry.dig('uros', 0, 'prs', 0, 'sound', 'audio')

关于json - Rubyist 测试数组中散列键的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63021622/

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