blob: 9ec34401ee5c6fa0d07b89d1784af223c2d3c6b6 [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
Antoine Pitroud9a51372012-06-29 01:58:26 +020010 Expecting property name enclosed in double quotes: line 1 column 2 (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:
34 json.dump(obj, outfile, sort_keys=True, indent=4)
35 outfile.write('\n')
Brett Cannon4b964f92008-05-05 20:21:38 +000036
37
38if __name__ == '__main__':
39 main()