ยปCore Development>Code coverage>Lib/json/tool.py

Python code coverage for Lib/json/tool.py

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