jq returning null as string if the json is empty

Viewed 17223

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?

2 Answers

First, a note: There's nothing inherently wrong with addr=null; you can just test for it:

if [[ $addr = null ]]; then ...code here...; fi

The rest of this answer pretends the above were untrue. :)


There are two practices that are notable as improving ease of error handling for this case:

  • Using set -o pipefail will detect whether any part -- not just the last component -- of a shell pipeline fails.
  • Using jq -e will cause jq's exit status to reflect whether it returned content that was either false or null.

Thus:

set -o pipefail
if addr=$(./xuez-cli getnetworkinfo | jq -er '.localaddresses[0].address'); then
  : "address retrieved successfully; this message is not logged unless set -x is active"
else
  echo "Running other logic here"
fi

...goes to Running other logic here if either jq fails (and -e specifies that false and null shall be treated as failures), or if xuez-cli reports an unsuccessful exit status.

Related