Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check jq result is null or not?

I'm using jq to parse some JSON. I want to check whether a property exists or not. If it exists I always want to get the first element in the array. Based on this I want to use if then ... else.

My code looks like this:

JSON_INPUT='{"var1":[{"foo":"bar"}],"var2":[{"fooooo":"baaaaar"}]}'
VAR2=$(echo $JSON_INPUT | jq  '.["var2"] | .[0]')
if [ -z "${VAR2}" ]
then
    echo "does not exist"
    # do some stuff...
else
    echo "exist"
    # do some stuff...
fi

The JSON_INPUT may contain var2 but must not. If it does not exist VAR2 will be null. But I'm not able to check for this null value. Where is the error?

like image 899
Raman Avatar asked Aug 15 '19 23:08

Raman


People also ask

Is null valid JSON?

JSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.

What does jq return?

jq normally returns with exit code 0 if the jq program and and input data are valid, regardless of the program's output. Adding the -e flag causes jq to return with exit code 1 if the output is null or false and 0 otherwise.

Can jq write JSON?

jq is an amazing little command line utility for working with JSON data. We've written before about how you can use jq to parse JSON on the command line, but in this post I want to talk about using jq to create JSON data from scratch or make changes to existing data.

What is jq query?

jq is like sed for JSON data - you can use it to slice and filter and map and transform structured data with the same ease that sed , awk , grep and friends let you play with text. jq is written in portable C, and it has zero runtime dependencies.


1 Answers

Where is the error?

Replace

[ -z "${VAR2}" ]

with

[ "${VAR2}" = "null" ]

because jq returns string null if var2 is not found in JSON file.


Or use --exit-status:

if echo "$JSON_INPUT" | jq --exit-status '.var2' >/dev/null; then 
  echo "exists"
else
  echo "does not exist"
fi
like image 192
Cyrus Avatar answered Oct 12 '22 14:10

Cyrus