在遍历值之前如何检查jq中是否存在“键" [英] How to check for presence of 'key' in jq before iterating over the values

查看:96
本文介绍了在遍历值之前如何检查jq中是否存在“键"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从下面的查询中获得了Cannot iterate over null (null),因为result对象中不存在.property_history.

I get Cannot iterate over null (null) from the below query because .property_history is not present in result object.

在继续进行map(...)之前,如何检查.property_history键的存在?

How do i check for the presence of .property_history key before proceeding with map(...) ?

我尝试使用类似sold_year= `echo "$content" | jq 'if has("property_history") then map(select(.event_name == "Sold"))[0].date' else null end

I tried using something like sold_year= `echo "$content" | jq 'if has("property_history") then map(select(.event_name == "Sold"))[0].date' else null end

原始查询:

sold_year=`echo "$content" | jq '.result.property_history | map(select(.event_name == "Sold"))[0].date'`

JSON:

{  
   "result":{  
      "property_history":[  
         {  
            "date":"01/27/2016",
            "price_changed":0,
            "price":899750,
            "event_name":"Listed",
            "sqft":0
         },
         {  
            "date":"12/15/2015",
            "price_changed":0,
            "price":899750,
            "event_name":"Listed",
            "sqft":2357
         },
         {  
            "date":"08/30/2004",
            "price_changed":0,
            "price":739000,
            "event_name":"Sold",
            "sqft":2357
         }
      ]
   }
}

推荐答案

您可以使用

You can use the select-expression in jq to do what you intend to achieve, something as,

jq '.result | select(.property_history != null) | .property_history | map(select(.event_name == "Sold"))[0].date'
"08/30/2004"

这篇关于在遍历值之前如何检查jq中是否存在“键"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆