Skip to content

Commit a47f396

Browse files
committed
Add indent support for json.tool
1 parent 1b8df10 commit a47f396

File tree

1 file changed

+25
-4
lines changed

1 file changed

+25
-4
lines changed

Lib/json/tool.py

Lines changed: 25 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,18 @@
1616
import sys
1717

1818

19+
def parse_indent(indent):
20+
"""Parse the argparse indent argument."""
21+
if indent == 'None':
22+
return None
23+
if indent == r'\t':
24+
return '\t'
25+
try:
26+
return int(indent)
27+
except ValueError:
28+
return indent
29+
30+
1931
def main():
2032
prog = 'python -m json.tool'
2133
description = ('A simple command line interface for json module '
@@ -25,24 +37,33 @@ def main():
2537
help='a JSON file to be validated or pretty-printed')
2638
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
2739
help='write the output of infile to outfile')
40+
parser.add_argument('--indent', default='4', type=parse_indent,
41+
help='Indent level or str for pretty-printing. '
42+
'Use None for the most compact representation. '
43+
r'Use "\t" for tab indentation.')
2844
parser.add_argument('--sort-keys', action='store_true', default=False,
2945
help='sort the output of dictionaries alphabetically by key')
3046
options = parser.parse_args()
3147

48+
# Read input JSON
3249
infile = options.infile or sys.stdin
33-
outfile = options.outfile or sys.stdout
34-
sort_keys = options.sort_keys
3550
with infile:
3651
try:
37-
if sort_keys:
52+
if options.sort_keys:
3853
obj = json.load(infile)
3954
else:
4055
obj = json.load(infile,
4156
object_pairs_hook=collections.OrderedDict)
4257
except ValueError as e:
4358
raise SystemExit(e)
59+
60+
# Export JSON
61+
outfile = options.outfile or sys.stdout
4462
with outfile:
45-
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
63+
json.dump(obj, outfile,
64+
indent=options.indent,
65+
sort_keys=options.sort_keys,
66+
)
4667
outfile.write('\n')
4768

4869

0 commit comments

Comments
 (0)