check if json is valid

Sometimes you might need to validate if json has correct structure. You can easily do it with command line utility “jq”.

So imagine you have two json files, one is valid and another one – corrupted:

[root@linux ~]# cat good.json
{"name":"John", "age":30, "car":null}
[root@linux ~]# jq '.' good.json
  "name": "John",
  "age": 30,
  "car": null
[root@linux ~]# cat bad.json
{"name":"John", "age":30, "car":null
[root@linux ~]# jq '.' bad.json
parse error: Unfinished JSON term at EOF at line 2, column 0
[root@linux ~]#

Validating them is easy, just check the exit code of the following command, like:

[root@linux ~]# [[ $(jq -e . < good.json &>/dev/null; echo $?) -eq 0 ]] && echo "json is valid" || echo "json not valid"
json is valid
[root@linux ~]# [[ $(jq -e . < bad.json &>/dev/null; echo $?) -eq 0 ]] && echo "json is valid" || echo "json not valid"
json not valid
[root@linux ~]#

When used with “-e”, jq sets the exit status of jq to 0 if the last output values was neither false nor null, 1 if the last output value was either false or null, or 4 if no valid result was ever produced. Normally jq exits with 2 if there was any usage problem or system error, 3 if there was a jq program compile error, or 0 if the jq program ran.