How can I validate the syntax of a JSON file in shell script without installing any package?
The simplest way to check if JSON is valid is to load the JSON into a JObject or JArray and then use the IsValid(JToken, JsonSchema) method with the JSON Schema. To get validation error messages, use the IsValid(JToken, JsonSchema, IList<String> ) or Validate(JToken, JsonSchema, ValidationEventHandler) overloads.
Validate a JSON Schema from the Command Line For schema validation, a Java tool called json-schema-validator comes in handy. This tool supports the syntax validation for the latest JSON schema draft v4. It can work standalone from the command line, or can be integrated into Maven build process as a plugin.
To check if a string is JSON in JavaScript, we can use the JSON. parse method within a try-catch block. to check if jsonStr is a valid JSON string. Since we created the JSON string by calling JSON.
json file is typically the first step in a Node project, and you need one to install dependencies in npm. If you're starting a project from scratch, you create a package.
I have yet to find a system where python -mjson.tool
doesn't work. So you can do:
python -mjson.tool "$somefile" > /dev/null
The exit code will be nonzero and you get the parse error on stderr if the file is not valid JSON.
Note: The Python libraries don't follow the JSON spec and allow NaN
and Infinity
as values. So using json.tool
will let some errors slip through. Still it's good enough for my use case of catching errors in human-written documents early.
Usually python
is installed on the system, so you can use it to parse JSON.
cat YOURFILENAME | python -c "import sys,json;json.loads(sys.stdin.read());print 'OK'"
I will print "OK" if the schema is valid.
Examples:
1.
$ echo {} | python -c "import sys,json;json.loads(sys.stdin.read());print 'OK'"
OK
2.
$ echo [] | python -c "import sys,json;json.loads(sys.stdin.read());print 'OK'"
OK
3.
$ echo 5 | python -c "import sys,json;json.loads(sys.stdin.read());print 'OK'"
OK
4.
$echo a | python -c "import sys,json;json.loads(sys.stdin.read());print 'OK'"
Traceback (most recent call last):
File "<string>", line 1, in <module>
File "/usr/lib/python2.7/json/__init__.py", line 338, in loads
return _default_decoder.decode(s)
File "/usr/lib/python2.7/json/decoder.py", line 366, in decode
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
File "/usr/lib/python2.7/json/decoder.py", line 384, in raw_decode
raise ValueError("No JSON object could be decoded")
ValueError: No JSON object could be decoded
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With