blob: ecf9c478850279776967c05cd040d1142e649eb2 [file] [log] [blame]
Christian Heimes90540002008-05-08 14:29:10 +00001r"""Command-line tool to validate and pretty-print JSON
2
3Usage::
4
Benjamin Petersonc6b607d2009-05-02 12:36:44 +00005 $ echo '{"json":"obj"}' | python -m json.tool
Christian Heimes90540002008-05-08 14:29:10 +00006 {
7 "json": "obj"
8 }
Benjamin Petersonc6b607d2009-05-02 12:36:44 +00009 $ echo '{ 1.2:3.4}' | python -m json.tool
Serhiy Storchakac510a042013-02-21 20:19:16 +020010 Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
Christian Heimes90540002008-05-08 14:29:10 +000011
12"""
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:
Ezio Melotti057bcb42012-11-29 02:15:18 +020021 infile = open(sys.argv[1], 'r')
Christian Heimes90540002008-05-08 14:29:10 +000022 outfile = sys.stdout
23 elif len(sys.argv) == 3:
Ezio Melotti057bcb42012-11-29 02:15:18 +020024 infile = open(sys.argv[1], 'r')
25 outfile = open(sys.argv[2], 'w')
Christian Heimes90540002008-05-08 14:29:10 +000026 else:
Benjamin Petersonc6b607d2009-05-02 12:36:44 +000027 raise SystemExit(sys.argv[0] + " [infile [outfile]]")
Ezio Melotti057bcb42012-11-29 02:15:18 +020028 with infile:
29 try:
30 obj = json.load(infile)
31 except ValueError as e:
32 raise SystemExit(e)
33 with outfile:
Ezio Melottib32512e2012-11-29 02:25:03 +020034 json.dump(obj, outfile, sort_keys=True,
35 indent=4, separators=(',', ': '))
Ezio Melotti057bcb42012-11-29 02:15:18 +020036 outfile.write('\n')
Christian Heimes90540002008-05-08 14:29:10 +000037
38
39if __name__ == '__main__':
40 main()