Check for valid json string or file with jq

Verifying if a string or file is valid json is easy with jq.

Check if a string is valid json

Using the -e argument, jq will return a 0 if the last output was neither false nor null.

1
2
3
4
5
if jq -e . >/dev/null 2>&1 <<<'{"test": "value"}'; then
    echo "parsed successfully"
else
    echo "could not parse json string"
fi

In addition, negating the above condition may increase readability:

1
2
3
4
if ! jq -e . >/dev/null 2>&1 <<<'{"test": "value"}'; then
    echo "could not parse json string"
    exit 1
fi

Using a variable:

1
2
3
4
if ! jq -e . >/dev/null 2>&1 <<<"$json"; then
    echo "could not parse json string"
    exit 1
fi

Check if a file is valid json

Using the same technique from above:

1
2
3
4
if ! jq -e . >/dev/null 2>&1 <<<$(cat invalid.json); then
    echo "could not parse json file"
    exit 1
fi

the invalid.json file:

1
{ "invalid"

will output:

1
could not parse json file