blob: cbd258ce24aeb7012121371d7cb8c6f42b9bcec8 [file] [log] [blame]
Brett Cannon4b964f92008-05-05 20:21:38 +00001r"""Command-line tool to validate and pretty-print JSON
2
3Usage::
4
5 $ echo '{"json":"obj"}' | python -mjson.tool
6 {
7 "json": "obj"
8 }
9 $ echo '{ 1.2:3.4}' | python -mjson.tool
10 Expecting property name: line 1 column 2 (char 2)
11"""
12import sys
13import json
14
15def main():
16 if len(sys.argv) == 1:
17 infile = sys.stdin
18 outfile = sys.stdout
19 elif len(sys.argv) == 2:
20 infile = open(sys.argv[1], 'rb')
21 outfile = sys.stdout
22 elif len(sys.argv) == 3:
23 infile = open(sys.argv[1], 'rb')
24 outfile = open(sys.argv[2], 'wb')
25 else:
26 raise SystemExit("{0} [infile [outfile]]".format(sys.argv[0]))
27 try:
28 obj = json.load(infile)
29 except ValueError, e:
30 raise SystemExit(e)
31 json.dump(obj, outfile, sort_keys=True, indent=4)
32 outfile.write('\n')
33
34
35if __name__ == '__main__':
36 main()