1 | n/a | r"""Command-line tool to validate and pretty-print JSON |
---|
2 | n/a | |
---|
3 | n/a | Usage:: |
---|
4 | n/a | |
---|
5 | n/a | $ echo '{"json":"obj"}' | python -m json.tool |
---|
6 | n/a | { |
---|
7 | n/a | "json": "obj" |
---|
8 | n/a | } |
---|
9 | n/a | $ echo '{ 1.2:3.4}' | python -m json.tool |
---|
10 | n/a | Expecting property name enclosed in double quotes: line 1 column 3 (char 2) |
---|
11 | n/a | |
---|
12 | n/a | """ |
---|
13 | n/a | import argparse |
---|
14 | n/a | import collections |
---|
15 | n/a | import json |
---|
16 | n/a | import sys |
---|
17 | n/a | |
---|
18 | n/a | |
---|
19 | n/a | def main(): |
---|
20 | n/a | prog = 'python -m json.tool' |
---|
21 | n/a | description = ('A simple command line interface for json module ' |
---|
22 | n/a | 'to validate and pretty-print JSON objects.') |
---|
23 | n/a | parser = argparse.ArgumentParser(prog=prog, description=description) |
---|
24 | n/a | parser.add_argument('infile', nargs='?', type=argparse.FileType(), |
---|
25 | n/a | help='a JSON file to be validated or pretty-printed') |
---|
26 | n/a | parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'), |
---|
27 | n/a | help='write the output of infile to outfile') |
---|
28 | n/a | parser.add_argument('--sort-keys', action='store_true', default=False, |
---|
29 | n/a | help='sort the output of dictionaries alphabetically by key') |
---|
30 | n/a | options = parser.parse_args() |
---|
31 | n/a | |
---|
32 | n/a | infile = options.infile or sys.stdin |
---|
33 | n/a | outfile = options.outfile or sys.stdout |
---|
34 | n/a | sort_keys = options.sort_keys |
---|
35 | n/a | with infile: |
---|
36 | n/a | try: |
---|
37 | n/a | if sort_keys: |
---|
38 | n/a | obj = json.load(infile) |
---|
39 | n/a | else: |
---|
40 | n/a | obj = json.load(infile, |
---|
41 | n/a | object_pairs_hook=collections.OrderedDict) |
---|
42 | n/a | except ValueError as e: |
---|
43 | n/a | raise SystemExit(e) |
---|
44 | n/a | with outfile: |
---|
45 | n/a | json.dump(obj, outfile, sort_keys=sort_keys, indent=4) |
---|
46 | n/a | outfile.write('\n') |
---|
47 | n/a | |
---|
48 | n/a | |
---|
49 | n/a | if __name__ == '__main__': |
---|
50 | n/a | main() |
---|