Raman
Raman

Reputation: 630

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?

Upvotes: 10

Views: 16674

Answers (2)

Cyrus
Cyrus

Reputation: 88583

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

Upvotes: 12

peak
peak

Reputation: 116690

I want to check whether a property exists or not. If it exists I always want to get the first element in the array ...

The condition can best be expressed as:

if has("var2")

so since you seem to want VAR2 to be null if the condition is not met, you could write:

VAR2=$(jq 'if has("var2") then .["var2"][0] else null end')

If the condition is not met, then we would find:

echo "$VAR2"
null

There is a small problem, here, though: for example, what if the array's first value is null?

So a more discriminating approach would be to write:

 VAR2=$(jq 'if has("var2") then .["var2"][0] else empty end')

Even if neither of these approaches is exactly what you want, they illustrate that putting as much of the logic inside the jq program as possible yields a tidy, easy-to-understand, and efficient solution.

Upvotes: 5

Related Questions