json 如何在迭代值之前检查 jq 中是否存在“键”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42097410/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check for presence of 'key' in jq before iterating over the values
提问by Rahul Dess
I get Cannot iterate over null (null)from the below query because .property_historyis not present in resultobject.
我Cannot iterate over null (null)从下面的查询中得到,因为对象中.property_history不存在result。
How do i check for the presence of .property_historykey before proceeding with map(...)?
.property_history在继续之前如何检查密钥是否存在map(...)?
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 'if has("property_history") then
map(select(.event_name == "Sold"))[0].date' else null end
Original Query:
原始查询:
sold_year=`echo "$content" | jq '.result.property_history | map(select(.event_name == "Sold"))[0].date'`
JSON:
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
}
]
}
}
回答by Inian
You can use the select-expressionin jqto do what you intend to achieve, something as,
您可以使用select-expressioninjq来执行您打算实现的目标,例如,
jq '.result | select(.property_history != null) | .property_history | map(select(.event_name == "Sold"))[0].date'
"08/30/2004"
回答by peak
You could use the ?post-fix operator:
您可以使用?post-fix 运算符:
$ jq '.result | .property_history? | .[] | select(.event_name == "Sold") | .date'
"08/30/2004"

