Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jq returning null as string if the json is empty

Tags:

bash

jq

I'm running this command do get a value from the json;

addr=$(./xuez-cli getnetworkinfo | jq -r '.localaddresses[0].address')

and it works just fine.

BUT if this .localaddresses[0].address part empty or doesn't even exist, jq sets the addr variable as null like this; addr=null

and I want to check if the json is empty/null and run some other command instead of parsing it as null string.

I couldn't find a way to work this around. How can I do this?

like image 574
Tolgahan Bozkurt Avatar asked Nov 03 '18 20:11

Tolgahan Bozkurt


People also ask

Can a JSON object be null?

Null valuesJSON 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.

Is Empty bash?

To find out if a bash variable is empty: Return true if a bash variable is unset or set to the empty string: if [ -z "$var" ]; Another option: [ -z "$var" ] && echo "Empty" Determine if a bash variable is empty: [[ ! -z "$var" ]] && echo "Not empty" || echo "Empty"


1 Answers

Something useful I found for shell scripts was:

jq '.foo // empty'

Which returns the match if successful, and the empty string if unsuccessful. So in bash I use:

addr=$(./xuez-cli getnetworkinfo | jq -r '.localaddresses[0].address // empty')

if [[ ! -z "$addr" ]]; then
    # do something
fi

Ref: https://github.com/stedolan/jq/issues/354#issuecomment-43147898 https://unix.stackexchange.com/questions/451479/jq-print-for-null-values

like image 155
Lood van Niekerk Avatar answered Sep 18 '22 11:09

Lood van Niekerk