2008-05-05 17:21:38 -03:00
|
|
|
r"""Command-line tool to validate and pretty-print JSON
|
|
|
|
|
|
|
|
Usage::
|
|
|
|
|
2009-03-17 20:19:00 -03:00
|
|
|
$ echo '{"json":"obj"}' | python -m json.tool
|
2008-05-05 17:21:38 -03:00
|
|
|
{
|
|
|
|
"json": "obj"
|
|
|
|
}
|
2009-03-17 20:19:00 -03:00
|
|
|
$ echo '{ 1.2:3.4}' | python -m json.tool
|
2013-02-21 14:17:54 -04:00
|
|
|
Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
|
2008-05-05 23:51:10 -03:00
|
|
|
|
2008-05-05 17:21:38 -03:00
|
|
|
"""
|
|
|
|
import sys
|
|
|
|
import json
|
|
|
|
|
|
|
|
def main():
|
|
|
|
if len(sys.argv) == 1:
|
|
|
|
infile = sys.stdin
|
|
|
|
outfile = sys.stdout
|
|
|
|
elif len(sys.argv) == 2:
|
|
|
|
infile = open(sys.argv[1], 'rb')
|
|
|
|
outfile = sys.stdout
|
|
|
|
elif len(sys.argv) == 3:
|
|
|
|
infile = open(sys.argv[1], 'rb')
|
|
|
|
outfile = open(sys.argv[2], 'wb')
|
|
|
|
else:
|
2009-03-17 20:19:00 -03:00
|
|
|
raise SystemExit(sys.argv[0] + " [infile [outfile]]")
|
2012-11-28 20:14:52 -04:00
|
|
|
with infile:
|
|
|
|
try:
|
|
|
|
obj = json.load(infile)
|
|
|
|
except ValueError, e:
|
|
|
|
raise SystemExit(e)
|
|
|
|
with outfile:
|
2012-11-28 20:22:49 -04:00
|
|
|
json.dump(obj, outfile, sort_keys=True,
|
|
|
|
indent=4, separators=(',', ': '))
|
2012-11-28 20:14:52 -04:00
|
|
|
outfile.write('\n')
|
2008-05-05 17:21:38 -03:00
|
|
|
|
|
|
|
|
|
|
|
if __name__ == '__main__':
|
|
|
|
main()
|