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?
Null valuesJSON has a special value called null which can be set on any type of data including arrays, objects, number and boolean types.
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.
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"
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With