From the manual:
-e / –exit-status:
Sets the exit status of jq to 0 if the last output values was neither false nor null, 1 if the last output value was either false or null, or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran.
So you can use:
if jq -e . >/dev/null 2>&1 <<<"$json_string"; then
echo "Parsed JSON successfully and got something other than false/null"
else
echo "Failed to parse JSON, or got false/null"
fi
In fact, if you don’t care about distinguishing between the different types of error, then you can just lose the -e
switch. In this case, anything considered to be valid JSON (including false/null) will be parsed successfully by the filter .
and the program will terminate successfully, so the if
branch will be followed.