Validate the syntax of JSON file in Unix?

Kavin Palaniswamy

Is there way to validate the syntax of a JSON file in Unix and move the invalid files into a error folder.

Thanks, Kavin

Blusky

You can try using a python oneliner:

python -c "import json;file = open('foo.json');json.loads(file.read());file.close()"

With some tweak, you can turn it into an alias:

testjson(){
    python -c "import json;file = open('$1');json.loads(file.read());file.close()"
}

And use something like this:

ls | while read file;
  testjson $file || mv $file ~/bad_json/
done;

Some sample with this:

echo "{}" > foo.json

echo "{" > bar.json

testjson bar.json && echo 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 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 2 (char 1)

testjson bar.json || echo ko
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 382, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting object: line 1 column 2 (char 1)
ko

testjson foo.json && echo ok
ok

testjson foo.json || echo ko

Note: just be careful with special filenames containing ' or \n

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related