jq is very powerful and I like it very much. But I confused when validate a JSON string with it.
123 and {"a:1 are invalid JSON, but they result are different. We can't validate it by jq output or exit value.
So, is there any way to validate a JSON string?
$ echo '123' | jq .
123
$ echo $?
0
$ echo '{"a": 1' | jq . // will not output anything
$ echo $?
0
$ echo '{"a":1}' | jq .
{
"a": 1
}
You have uncovered a (by now well-known) bug that was introduced relatively recently.
In any case, jq is not always reliable as a JSON validator, which is not to say it isn't useful as such in practice.
If you just want to test the validity of a purported JSON entity, then I would suggest as a workaround that you use type as the filter instead of ..
For example, using the buggy version of jq:
$ echo '{"a": 1' | jq .
$ echo '{"a": 1' | jq type
$
That is, instead of a jq type, the result is the empty stream. So, by testing both the return code and the emitted value(s), one can get a more accurate picture of the validity of the input.
@pkoppstein
Thank you very much~
jq type will be my solution. It likes JSON_TYPE function of MySQL 5.7
Most helpful comment
You have uncovered a (by now well-known) bug that was introduced relatively recently.
In any case, jq is not always reliable as a JSON validator, which is not to say it isn't useful as such in practice.
If you just want to test the validity of a purported JSON entity, then I would suggest as a workaround that you use
typeas the filter instead of..For example, using the buggy version of jq:
That is, instead of a jq type, the result is the empty stream. So, by testing both the return code and the emitted value(s), one can get a more accurate picture of the validity of the input.