1r"""Command-line tool to validate and pretty-print JSON
2
3Usage::
4
5    $ echo '{"json":"obj"}' | python -m json.tool
6    {
7        "json": "obj"
8    }
9    $ echo '{ 1.2:3.4}' | python -m json.tool
10    Expecting property name enclosed in double quotes: line 1 column 3 (char 2)
11
12"""
13import argparse
14import json
15import sys
16
17
18def main():
19    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    parser.add_argument('--sort-keys', action='store_true', default=False,
28                        help='sort the output of dictionaries alphabetically by key')
29    options = parser.parse_args()
30
31    infile = options.infile or sys.stdin
32    outfile = options.outfile or sys.stdout
33    sort_keys = options.sort_keys
34    with infile:
35        try:
36            obj = json.load(infile)
37        except ValueError as e:
38            raise SystemExit(e)
39    with outfile:
40        json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
41        outfile.write('\n')
42
43
44if __name__ == '__main__':
45    main()
46