blob: cd57e4f5ae0a33cfaadcf681a69774e83acda283 [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"""
Benjamin Peterson940e2072014-03-21 23:17:29 -050013import argparse
Christian Heimes90540002008-05-08 14:29:10 +000014import json
Benjamin Peterson940e2072014-03-21 23:17:29 -050015import sys
16
Christian Heimes90540002008-05-08 14:29:10 +000017
18def main():
Benjamin Peterson940e2072014-03-21 23:17:29 -050019 prog = 'python -m json.tool'
20 description = ('A simple command line interface for json module '
21 'to validate and pretty-print JSON objects.')
22 parser = argparse.ArgumentParser(prog=prog, description=description)
23 parser.add_argument('infile', nargs='?', type=argparse.FileType(),
24 help='a JSON file to be validated or pretty-printed')
25 parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
26 help='write the output of infile to outfile')
27 options = parser.parse_args()
28
29 infile = options.infile or sys.stdin
30 outfile = options.outfile or sys.stdout
Ezio Melotti057bcb42012-11-29 02:15:18 +020031 with infile:
32 try:
33 obj = json.load(infile)
34 except ValueError as e:
35 raise SystemExit(e)
36 with outfile:
37 json.dump(obj, outfile, sort_keys=True, indent=4)
38 outfile.write('\n')
Christian Heimes90540002008-05-08 14:29:10 +000039
40
41if __name__ == '__main__':
42 main()