blob: fc5d74923df2abef7a6c94e2d34eba7c13fecded [file] [log] [blame]
Brett Cannon4b964f92008-05-05 20:21:38 +00001r"""Command-line tool to validate and pretty-print JSON
2
3Usage::
4
Bob Ippolitod914e3f2009-03-17 23:19:00 +00005 $ echo '{"json":"obj"}' | python -m json.tool
Brett Cannon4b964f92008-05-05 20:21:38 +00006 {
7 "json": "obj"
8 }
Bob Ippolitod914e3f2009-03-17 23:19:00 +00009 $ echo '{ 1.2:3.4}' | python -m json.tool
Serhiy Storchaka49d40222013-02-21 20:17:54 +020010 Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
Benjamin Peterson0b7f7782008-05-06 02:51:10 +000011
Brett Cannon4b964f92008-05-05 20:21:38 +000012"""
13import sys
14import json
15
16def main():
17 if len(sys.argv) == 1:
18 infile = sys.stdin
19 outfile = sys.stdout
20 elif len(sys.argv) == 2:
21 infile = open(sys.argv[1], 'rb')
22 outfile = sys.stdout
23 elif len(sys.argv) == 3:
24 infile = open(sys.argv[1], 'rb')
25 outfile = open(sys.argv[2], 'wb')
26 else:
Bob Ippolitod914e3f2009-03-17 23:19:00 +000027 raise SystemExit(sys.argv[0] + " [infile [outfile]]")
Ezio Melottid8feba92012-11-29 02:14:52 +020028 with infile:
29 try:
30 obj = json.load(infile)
31 except ValueError, e:
32 raise SystemExit(e)
33 with outfile:
Ezio Melottidef6ee52012-11-29 02:22:49 +020034 json.dump(obj, outfile, sort_keys=True,
35 indent=4, separators=(',', ': '))
Ezio Melottid8feba92012-11-29 02:14:52 +020036 outfile.write('\n')
Brett Cannon4b964f92008-05-05 20:21:38 +000037
38
39if __name__ == '__main__':
40 main()