jsonbashjq

How to check for presence of 'key' in jq before iterating over the values


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
            }
        ]
    }
}

Solution

  • 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'