Try jsonlint:

sudo apt install jsonlint

The basic usage syntax is

jsonlint YOUR-FILE.JSON

You find its manual by typing man jsonlint or visiting its online manpage:

An excerpt:

NAME
       jsonlint - A JSON syntax validator and formatter tool

SYNOPSIS
       jsonlint [-v][-s|-S][-f|-F][-ecodec]inputfile.json...

[...]

OPTIONS
       The  return  status  will  be  0 if the file is legal JSON, or non-zero
       otherwise.  Use -v to see the warning details.

       [...]

       -v, --verbose
              Show details of lint checking
       -s, --strict
              Be strict in what is considered legal JSON (the default)
       -S, --nonstrict
              Be loose in what is considered legal JSON
       -f, --format
              Reformat the JSON (if legal) to stdout

[...]

So you can see whether your JSON is valid by checking the return code of jsonlint. You can see it by running echo $? right afterwards (0=OK, 1=invalid), or by evaluating it using &&, || or if.

Answer from Byte Commander on askubuntu.com
Top answer
1 of 2
2

Without the need for a specific application, if you just want to separate the wheat from the chaff, and have PHP installed on the Linux machine, you can use a simple one-liner for this:

for json in folder/*; do php -r "if ( ! \$foo=json_decode(file_get_contents('$json')) ) echo \"$json\n\";"; done

This would list all broken .json files in the directory named folder. Take out the exlamation mark (!) to only list the .json files which are fine.

It might well be PHP spits out some additional error message here. If that happens, just re-direct error output (STDERR) to the machine's black hole (/dev/null):

for json in folder/*; do php -r "if ( ! \$foo=json_decode(file_get_contents('$json')) ) echo \"$json\n\";" 2>/dev/null; done

TL;DR – a short explanation of what that one-liner does

  • for json in folder/*; do […] done: loop over all .json files in the given location. On each iteration, store the file name into a variable named $json.
  • php -r: invoke the PHP executable. The -r parameter tells it to (r)un a command instead of expecting a file. The command must directly follow this, separated by white-space.
  • "[…]": using double-quotes, we can easier integrate shell variables. The price is we have to escape all $ signs belonging to PHP variables.
  • \$foo: see previous point, we need to escape the $ here.
  • $foo=json_decode(file_get_contents('$json')): have PHP reading the file (file_get_contents; the $json here is our Bash variable from the first bullet-point), then convert the JSON to a PHP object (json_decode). We don't want to see the result, so we assign it to a variable ($foo in my example).
    If decoding was successful, the assignment will return TRUE, otherwise FALSE – which is why we can use this construction as our "if condition".
  • if ( […] ) echo \"$json\n\";": only write the file name (this again is our Bash variable here) to the console if our condition is met – to "separate the wheat from the chaff", as I've put it initially. As usual in PHP, the command needs to be terminated by a semi-colon (;). Also note that I needed to escape the double-quotes here, so our "outer Shell wrapper" doesn't end prematurely. I needed the double-quotes, so \n is interpreted as "new line" – with single-quotes, it would print a literal \n instead.
  • 2>/dev/null: Redirect error output (STDERR) to the "black hole" (i.e. don't show any errors if they occur). Our echo commands go to STDOUT, and thus are not affected by this.
2 of 2
0

You can use jsonlint:

  • CLI
  • open source (written in JavaScript)
  • check whether file(s) are valid:

Example:

# Install
sudo apt-get install -y nodejs npm
sudo npm install jsonlint -g
sudo ln -s /usr/bin/nodejs /usr/bin/node # to avoid "/usr/bin/env: node: No such file or directory" error
jsonlint -qc *.json

# Use
ubuntu@pm:~/pubmed/pubmed$ jsonlint --compact --validate *.json
my_file_bad.json: line 279916, col 18, found: 'EOF' - expected: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['.
ubuntu@pm:~/pubmed/pubmed$

Useful options:

   -c, --compact            compact error display
   -V, --validate           a JSON schema to use for validation
🌐
Ubuntu
manpages.ubuntu.com › manpages › bionic › man1 › validate-json.1.html
Ubuntu Manpage: validate-json - JSON Schema command line interface
--dump-schema Output full schema and exit --dump-schema-url Output URL of schema --verbose Show additional output --quiet Suppress all output -h --help Show this help validate-json 5.2.6 October 2017
🌐
Xmodulo
xmodulo.com › validate-json-command-line-linux.html
How to validate JSON from the command line on Linux
November 25, 2020 - This tutorial describes how to validate JSON data and JSON schema from the command line on Linux.
🌐
Linux.com
linux.com › home › training and tutorials › how to validate json from the command line on linux
How to validate JSON from the command line on Linux - Linux.com
March 29, 2016 - Due to its syntactic simplicity and flexibility, JSON (JavaScript Object Notation) has become pretty much the de-facto standard data exchange format in many web applications. As JSON becomes widely used to represent structured data with a great degree of flexibility, the need arises for being able to “validate” a JSON representation.
🌐
Linux Hint
linuxhint.com › validate-json-files-from-command-line-linux
How to Validate JSON from the Command Line on Linux – Linux Hint
Validating JSON from the command line can be done using JSON Spec, jq and jsonlint. These tools can validate the JSON data, providing feedback on any errors.
🌐
Ubuntu
manpages.ubuntu.com › manpages › jammy › man1 › json-glib-validate.1.html
Ubuntu Manpage: json-glib-validate - JSON-GLib validation tool
json-glib-validate offers a simple command line interface to validate JSON data. It lets you list URIs that point to JSON data and checks that the data conforms to the JSON syntax.
Find elsewhere
🌐
Ubuntu
manpages.ubuntu.com › manpages › trusty › man1 › jsonlint.1.html
Ubuntu Manpage: jsonlint - A JSON syntax validator and formatter tool
Options are: -v, -s, -S, -f, -F, -e -v, --verbose Show details of lint checking -s, --strict Be strict in what is considered legal JSON (the default) -S, --nonstrict Be loose in what is considered legal JSON -f, --format Reformat the JSON (if legal) to stdout -F, --format-compactly Reformat the JSON simlar to -f, but do so compactly by removing all unnecessary whitespace -e codec, --encoding=codec --input-encoding=codec --output-encoding=codec Set the input and output character encoding codec (e.g., ascii, utf8, utf-16). The -e will set both the input and output encodings to the same thing. If not supplied, the input encoding is guessed according to the JSON specification.
🌐
#!/bin/bash
shscripts.com › home › check if json is valid
check if json is valid - #!/bin/bash
March 18, 2024 - [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. It sets it to 1 if the last output value was either false or null, or 4 if no valid result was ever produced.
🌐
GitHub
github.com › zaach › jsonlint
GitHub - zaach/jsonlint: A JSON parser and validator with a CLI. · GitHub
Install jsonlint with npm to use the command line interface: ... $ jsonlint -h Usage: jsonlint [file] [options] file file to parse; otherwise uses stdin Options: -v, --version print version and exit -s, --sort-keys sort object keys -i, --in-place overwrite the file -t CHAR, --indent CHAR character(s) to use for indentation [ ] -c, --compact compact error display -V, --validate a JSON schema to use for validation -e, --environment which specification of JSON Schema the validation file uses [json-schema-draft-03] -q, --quiet do not print the parsed json to STDOUT [false] -p, --pretty-print force pretty printing even if invalid
Starred by 2K users
Forked by 415 users
Languages   JavaScript 91.2% | HTML 3.8% | Yacc 3.0% | Lex 1.1% | Makefile 0.9%
🌐
JSON Type Definition
jsontypedef.com › docs › jtd-validate
Validating JSON data in shell scripts with jtd-validate
jtd-validate is a CLI tool that can validate JSON input against a JSON Typedef schema. It lives on GitHub here. This article will go over why jtd-validate may be useful to you, how to install it, and then go through an example of using jtd-validate ...
🌐
Nidkil
nidkil.me › 2018 › 02 › 23 › validating-a-json-file-from-the-command-line-in-linux
Validating a json file from the command line in Linux | Adventures of a space monkey
February 23, 2018 - Yes, I know this is not in line with the spec, but it is damn handy for understanding the file. So I needed to strip the comments to valiate the file. After googeling around a bit I found an awk command to do just this. Try the following command. awk '{sub(/\/.*$/,"")}1' settings.analyzer.json > settings.analyzer.json
🌐
GitHub
github.com › martinlindhe › validjson
GitHub - martinlindhe/validjson: Command line tool to validate JSON syntax of input file.
Command line tool to validate and pretty-print JSON syntax of input files.
Author   martinlindhe
🌐
Medium
pavolkutaj.medium.com › how-to-check-the-validity-of-json-with-jq-in-bash-scripts-21523418f67d
How To Check the Validity of JSON with jq in bash scripts | by Pavol Z. Kutaj | Medium
February 21, 2024 - json_data='{"key": "value", "invalid_key": "missing_quote"}' set +e retval=$(jq -re '""' <<<"${json_data}" 2>&1) if [ -z "${retval}" ]; then echo "JSON parsing successful" else echo "ERROR: jq - ${retval}" fi # >>> ERROR: jq - jq: parse error: Unfinished string at EOF at line 2, column 0
🌐
Baeldung
baeldung.com › home › scripting › parsing, validating, and printing json in shell scripts
Parsing, Validating, and Printing JSON in Shell Scripts | Baeldung on Linux
March 18, 2024 - $ echo '{"field":"data", "array": ["i1", "i2"], "object":{"subfield":"subdata"}}' | json_pp { "array" : [ "i1", "i2" ], "field" : "data", "object" : { "subfield" : "subdata" } } $ echo 'INVALID' | json_pp malformed JSON string, neither array, object, number, string or atom, at character offset 0 (before "INVALID\n") at /usr/bin/json_pp line 59. As the example shows, the json_pp tool that comes with the JSON::PP Perl core module can prettify and validate a JSON object.
🌐
Commandlinefu
commandlinefu.com › commands › view › 24247 › use-jq-to-validate-and-pretty-print-json-output
use jq to validate and pretty-print json output Using cat
cat file.json | jq - (use jq to validate and pretty-print json output the `jq` tool can also be used do validate json files and pretty print output `cat file.json | jq` available on several platforms, including newer debian-based systems via `#sudo apt install jq`, mac via `brew install jq`, ...