Mercurial > repos > rliterman > csp2
comparison CSP2/CSP2_env/env-d9b9114564458d9d-741b3de822f2aaca6c6caa4325c4afce/lib/python3.8/json/tool.py @ 68:5028fdace37b
planemo upload commit 2e9511a184a1ca667c7be0c6321a36dc4e3d116d
author | jpayne |
---|---|
date | Tue, 18 Mar 2025 16:23:26 -0400 |
parents | |
children |
comparison
equal
deleted
inserted
replaced
67:0e9998148a16 | 68:5028fdace37b |
---|---|
1 r"""Command-line tool to validate and pretty-print JSON | |
2 | |
3 Usage:: | |
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 """ | |
13 import argparse | |
14 import json | |
15 import sys | |
16 | |
17 | |
18 def 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='?', | |
24 type=argparse.FileType(encoding="utf-8"), | |
25 help='a JSON file to be validated or pretty-printed', | |
26 default=sys.stdin) | |
27 parser.add_argument('outfile', nargs='?', | |
28 type=argparse.FileType('w', encoding="utf-8"), | |
29 help='write the output of infile to outfile', | |
30 default=sys.stdout) | |
31 parser.add_argument('--sort-keys', action='store_true', default=False, | |
32 help='sort the output of dictionaries alphabetically by key') | |
33 parser.add_argument('--json-lines', action='store_true', default=False, | |
34 help='parse input using the jsonlines format') | |
35 options = parser.parse_args() | |
36 | |
37 infile = options.infile | |
38 outfile = options.outfile | |
39 sort_keys = options.sort_keys | |
40 json_lines = options.json_lines | |
41 with infile, outfile: | |
42 try: | |
43 if json_lines: | |
44 objs = (json.loads(line) for line in infile) | |
45 else: | |
46 objs = (json.load(infile), ) | |
47 for obj in objs: | |
48 json.dump(obj, outfile, sort_keys=sort_keys, indent=4) | |
49 outfile.write('\n') | |
50 except ValueError as e: | |
51 raise SystemExit(e) | |
52 | |
53 | |
54 if __name__ == '__main__': | |
55 main() |