2008-05-08 11:29:10 -03:00
|
|
|
r"""Command-line tool to validate and pretty-print JSON
|
|
|
|
|
|
|
|
Usage::
|
|
|
|
|
2009-05-02 09:36:44 -03:00
|
|
|
$ echo '{"json":"obj"}' | python -m json.tool
|
2008-05-08 11:29:10 -03:00
|
|
|
{
|
|
|
|
"json": "obj"
|
|
|
|
}
|
2009-05-02 09:36:44 -03:00
|
|
|
$ echo '{ 1.2:3.4}' | python -m json.tool
|
2012-06-28 20:58:26 -03:00
|
|
|
Expecting property name enclosed in double quotes: line 1 column 2 (char 2)
|
2008-05-08 11:29:10 -03:00
|
|
|
|
|
|
|
"""
|
|
|
|
import sys
|
|
|
|
import json
|
|
|
|
|
|
|
|
def main():
|
|
|
|
if len(sys.argv) == 1:
|
|
|
|
infile = sys.stdin
|
|
|
|
outfile = sys.stdout
|
|
|
|
elif len(sys.argv) == 2:
|
2012-11-28 20:15:18 -04:00
|
|
|
infile = open(sys.argv[1], 'r')
|
2008-05-08 11:29:10 -03:00
|
|
|
outfile = sys.stdout
|
|
|
|
elif len(sys.argv) == 3:
|
2012-11-28 20:15:18 -04:00
|
|
|
infile = open(sys.argv[1], 'r')
|
|
|
|
outfile = open(sys.argv[2], 'w')
|
2008-05-08 11:29:10 -03:00
|
|
|
else:
|
2009-05-02 09:36:44 -03:00
|
|
|
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
|
2012-11-28 20:15:18 -04:00
|
|
|
with infile:
|
|
|
|
try:
|
|
|
|
obj = json.load(infile)
|
|
|
|
except ValueError as e:
|
|
|
|
raise SystemExit(e)
|
|
|
|
with outfile:
|
2012-11-28 20:25:03 -04:00
|
|
|
json.dump(obj, outfile, sort_keys=True,
|
|
|
|
indent=4, separators=(',', ': '))
|
2012-11-28 20:15:18 -04:00
|
|
|
outfile.write('\n')
|
2008-05-08 11:29:10 -03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|