How To Check the Validity of JSON with jq in bash scripts

Pavol Kutaj
1 min readFeb 21, 2024

--

The aim of this page📝 is to explain JSON parsing in shell scripting based on troubleshooting parsing errors with jq.

  • jq is a widely used command-line tool for parsing and manipulating JSON data.
  • Introducing syntax errors in JSON can lead to parsing failures, helping in error testing.
  • Using jq -re '""' allows validation of JSON data without processing its contents.
  • The -r flag in jq is used to output raw strings without additional formatting.
  • The -e flag in jq sets the exit status to 1 in case of parsing errors.
  • Modifying JSON data to introduce errors is a common practice for testing error handling.
  • Checking the length of the output variable can indicate the success or failure of JSON parsing.
json_data='{"key": "value", "invalid_key": "missing_quote"}'
set +e
retval=$(jq -re '""' <<<"${json_data}" 2>&1)
if [ -z "${retval}" ]; then
echo "JSON parsing successful"
else
echo "ERROR: jq - ${retval}"
fi
# >>> ERROR: jq - jq: parse error: Unfinished string at EOF at line 2, column 0

--

--

No responses yet