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