how.wtf

Check for valid json string or file with jq

· Thomas Taylor

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.

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

In addition, negating the above condition may increase readability:

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

Using a variable:

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

Check if a file is valid json

Using the same technique from above:

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

the invalid.json file:

1{ "invalid"

will output:

1could not parse json file

#linux  

Reply to this post by email ↪