Skip to content

Commit fadb45e

Browse files
committed
bpo-30971: Improve code readability of json.tool
Originall from #2720 Set default option for infile and outfile as per #2720 (review) Use --sort-keys help message based on the json.tool docs at https://docs.python.org/3.6/library/json.html#basic-usage: Remove commens as per https://bugs.python.org/msg298692. Code was descriptive without the comments.
1 parent fff2a21 commit fadb45e

File tree

1 file changed

+10
-13
lines changed

1 file changed

+10
-13
lines changed

Lib/json/tool.py

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -22,27 +22,24 @@ def main():
2222
'to validate and pretty-print JSON objects.')
2323
parser = argparse.ArgumentParser(prog=prog, description=description)
2424
parser.add_argument('infile', nargs='?', type=argparse.FileType(),
25+
default=sys.stdin,
2526
help='a JSON file to be validated or pretty-printed')
2627
parser.add_argument('outfile', nargs='?', type=argparse.FileType('w'),
28+
default=sys.stdout,
2729
help='write the output of infile to outfile')
28-
parser.add_argument('--sort-keys', action='store_true', default=False,
29-
help='sort the output of dictionaries alphabetically by key')
30+
parser.add_argument('--sort-keys', action='store_true',
31+
help='sort the output of dictionaries by key')
3032
options = parser.parse_args()
3133

32-
infile = options.infile or sys.stdin
33-
outfile = options.outfile or sys.stdout
34-
sort_keys = options.sort_keys
35-
with infile:
34+
hook = collections.OrderedDict if options.sort_keys else None
35+
with options.infile as infile:
3636
try:
37-
if sort_keys:
38-
obj = json.load(infile)
39-
else:
40-
obj = json.load(infile,
41-
object_pairs_hook=collections.OrderedDict)
37+
obj = json.load(infile, object_pairs_hook=hook)
4238
except ValueError as e:
4339
raise SystemExit(e)
44-
with outfile:
45-
json.dump(obj, outfile, sort_keys=sort_keys, indent=4)
40+
41+
with options.outfile as outfile:
42+
json.dump(obj, outfile, sort_keys=options.sort_keys, indent=4)
4643
outfile.write('\n')
4744

4845

0 commit comments

Comments
 (0)