jq returning null as string if the json is 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


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.

Tags:

Bash

Jq