我正在运行下面的API调用,并将列表传递给vhost,然后传递到另一个API,并获得一些值,这些都很好。
response = conn.get("/api/vhosts")
statistics = JSON.parse(response.body)
statistics.each do |vhosts|
response1 = conn.get("/api/exchanges/#{vhosts["name"]}/direct_queue_exchange")
statistics1 = JSON.parse(response1.body)
statistics1.fetch("message_stats").fetch("publish_in_details").fetch("rate")
end样本输出:
output -1 - {"error"=>"Object Not Found", "reason"=>"Not Found"}
output -2 - {"message_stats"=>{"publish_in_details"=>{"rate"=>0.0}, "publish_in"=>91, "publish_out_details"=>{"rate"=>0.0}, "publish_out"=>91}, "outgoing"=>[], "incoming"=>[], "user_who_performed_action"=>"user_122f5b58", "arguments"=>{}, "internal"=>false, "auto_delete"=>false, "durable"=>true, "type"=>"direct", "vhost"=>"vhost_2388ce36", "name"=>"direct_queue_exchange"}
{"outgoing"=>[], "incoming"=>[], "user_who_performed_action"=>"user_d6b8f477", "arguments"=>{}, "internal"=>false, "auto_delete"=>false, "durable"=>true, "type"=>"direct", "vhost"=>"vhost_37892b86", "name"=>"direct_queue_exchange"}我在获取我想要的值时遇到了问题。例如,在我的代码中,我获取这些值,比如“速率”,我得到了这个错误:key not found: "message_stats",因为有些输出不包含我正在查找的键
我怎么能忽略像这样的{"error"=>"Object Not Found", "reason"=>"Not Found"}输出
发布于 2018-03-07 10:27:55
如果我没弄错你的问题,有几种方法可以做到:
在Ruby2.3及以上版本(感谢@Steve )
statistics1.dig('message_stats', 'publish_in_details', 'rate')与您的类似,如果找不到键,fetch的第二个参数将设置默认值:
statistics1.fetch("message_stats", {}).fetch("publish_in_details", {}).fetch("rate", nil)或者你可以这样做:
message_stats = statistics1['message_stats']
next unless message_stats
publish_in_details = message_stats['publish_in_details']
next unless publish_in_details
publish_in_details['rate']发布于 2018-03-07 10:27:39
如果键不存在,可以使用#fetch中的默认选项返回空哈希。
statistics1.fetch("message_stats", ()).fetch("publish_in_details", {}).fetch("rate", nil)即使simper也是#dig方法。
statistics1.dig("message_stats", "publish_in_details", "rate")如果缺少任何键,nil将优雅地返回。
发布于 2018-03-07 10:33:13
另外两个也为您的问题提供了解决方案,下面是对相同问题的描述。
fetch(key_name) # get the value if the key exists, raise a KeyError if it doesn't
fetch(key_name, default_value) # get the value if the key exists, return default_value otherwise因此,使用下面将解决您的问题。
statistics1.fetch("message_stats", ()).fetch("publish_in_details", {}).fetch("rate", nil)此外,您还可以检查是否存在错误,然后相应地处理案例。
if fetch("message_stats", false)
statistics1.fetch("message_stats").fetch("publish_in_details").fetch("rate")
endhttps://stackoverflow.com/questions/49149289
复制相似问题