How to check for presence of 'key' in jq before iterating over the values
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"
use has("mykey1")
(for objects) or has(0)
(for arrays):
jq 'has("name")' <<< "{\"name\": \"hello\"}"
output:
true
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'