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 collections
15import json
16import sys
17
18
19def main():
20    prog = 'python -m json.tool'
21    description = ('A simple command line interface for json module '
22                   'to validate and pretty-print JSON objects.')
23    parser = argparse.ArgumentParser(prog=prog, description=description)
24    parser.add_argument('infile', nargs='?', type=argparse.FileType(),
25                        help='a JSON file to be validated or pretty-printed')
26    parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
27                        help='write the output of infile to outfile')
28    parser.add_argument('--sort-keys', action='store_true', default=False,
29                        help='sort the output of dictionaries alphabetically by key')
30    options = parser.parse_args()
31
32    infile = options.infile or sys.stdin
33    outfile = options.outfile or sys.stdout
34    sort_keys = options.sort_keys
35    with infile:
36        try:
37            if sort_keys:
38                obj = json.load(infile)
39            else:
40                obj = json.load(infile,
41                                object_pairs_hook=collections.OrderedDict)
42        except ValueError as e:
43            raise SystemExit(e)
44    with outfile:
45        json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
46        outfile.write('\n')
47
48
49if __name__ == '__main__':
50    main()
51