Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

json

bash

jq

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          }       ]    } } 
like image 238
Rahul Dess Avatar asked Feb 07 '17 18:02

Rahul Dess


People also ask

How do you remove quotes from JQ output?

If you want to strip the quotes, just pipe the output from this command to tr -d '"' .

What is JQ query?

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.


1 Answers

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' 
like image 124
Inian Avatar answered Oct 07 '22 11:10

Inian