I get Cannot iterate over null (null)
from the below query because .property_history
is not present in result
object.
How do i check for the presence of .property_history
key before proceeding with 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
Original Query:
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 } ] } }
If you want to strip the quotes, just pipe the output from this command to tr -d '"' .
A jq program is a "filter": it takes an input, and produces an output. There are a lot of builtin filters for extracting a particular field of an object, or converting a number to a string, or various other standard tasks.
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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With