From 03257949bc02a4afdf2ea1eb07a73f8128129579 Mon Sep 17 00:00:00 2001 From: Daniel Himmelstein Date: Wed, 4 Dec 2019 01:15:19 -0500 Subject: bpo-29636: Add --(no-)indent arguments to json.tool (GH-345) --- Lib/json/tool.py | 30 +++++++++++++++++++++++------- 1 file changed, 23 insertions(+), 7 deletions(-) (limited to 'Lib/json/tool.py') diff --git a/Lib/json/tool.py b/Lib/json/tool.py index b3ef9923e3..6c687d77c5 100644 --- a/Lib/json/tool.py +++ b/Lib/json/tool.py @@ -30,20 +30,36 @@ def main(): help='sort the output of dictionaries alphabetically by key') parser.add_argument('--json-lines', action='store_true', default=False, help='parse input using the jsonlines format') + group = parser.add_mutually_exclusive_group() + group.add_argument('--indent', default=4, type=int, + help='separate items with newlines and use this number ' + 'of spaces for indentation') + group.add_argument('--tab', action='store_const', dest='indent', + const='\t', help='separate items with newlines and use ' + 'tabs for indentation') + group.add_argument('--no-indent', action='store_const', dest='indent', + const=None, + help='separate items with spaces rather than newlines') + group.add_argument('--compact', action='store_true', + help='suppress all whitespace separation (most compact)') options = parser.parse_args() - infile = options.infile - outfile = options.outfile - sort_keys = options.sort_keys - json_lines = options.json_lines - with infile, outfile: + dump_args = { + 'sort_keys': options.sort_keys, + 'indent': options.indent, + } + if options.compact: + dump_args['indent'] = None + dump_args['separators'] = ',', ':' + + with options.infile as infile, options.outfile as outfile: try: - if json_lines: + if options.json_lines: objs = (json.loads(line) for line in infile) else: objs = (json.load(infile), ) for obj in objs: - json.dump(obj, outfile, sort_keys=sort_keys, indent=4) + json.dump(obj, outfile, **dump_args) outfile.write('\n') except ValueError as e: raise SystemExit(e) -- cgit v1.2.1