Jq: How to validate a JSON string with jq?

Created on 26 Nov 2017  路  2Comments  路  Source: stedolan/jq

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
}

Most helpful comment

  1. You have uncovered a (by now well-known) bug that was introduced relatively recently.

  2. 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.

  3. 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.

All 2 comments

  1. You have uncovered a (by now well-known) bug that was introduced relatively recently.

  2. 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.

  3. 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

Was this page helpful?
0 / 5 - 0 ratings

Related issues

lhunath picture lhunath  路  3Comments

tbelaire picture tbelaire  路  4Comments

rokka-n picture rokka-n  路  4Comments

sloanlance picture sloanlance  路  3Comments

tischwa picture tischwa  路  4Comments