在迭代这些值之前,如何检查 jq 中是否存在“ key”

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

在使用 map(...)之前,我如何检查 .property_history密钥的存在?

我尝试使用诸如 < code > sell _ year = ‘ echo“ $content”| jq‘ if has (“ property _ history”)之类的命令 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'`

杰森:

{
"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
}
]
}
}
105823 次浏览

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'

Technically, to test for the presence of a property, you should use has/1, but in the present context, it would probably be better to use the postfix ? operator, e.g.:

$ jq '.result
| .property_history[]?
| select(.event_name == "Sold")
| .date'
"08/30/2004"

The trick is to use // together with empty:

jq '.result.property_history // empty | map(select(.event_name == "Sold"))[0:1][].date'

Another alternative is to use an additional select:

jq '.result.property_history | select(.) | map(select(.event_name == "Sold"))[0:1][].date'

General pattern:

try (...) // "default_value"

With your logic:

jq 'try (.result.property_history | map(select(.event_name == "Sold"))[0].date) // "default_value"'

try (without a catch) returns empty if the expression fails. // provides a default value if the value is empty.

use has("mykey1") (for objects) or has(0) (for arrays):

jq 'has("name")' <<< "{\"name\": \"hello\"}"

output:

true