Skip to content

bpo-45644 Make json.tool soak up infile before writing to outfile #29269

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,18 @@
import argparse
import json
import sys
from pathlib import Path


def pathtype(path):
class wrapped_fd:
'Make stdin and stdout have open() like a `pathlib.Path`'
def __init__(self, file_descriptor):
self.fd = file_descriptor

def open(self, *args, **kwargs):
return self.fd
return wrapped_fd(path) if path in (sys.stdin, sys.stderr) else Path(path)


def main():
Expand All @@ -21,11 +33,11 @@ def main():
'to validate and pretty-print JSON objects.')
parser = argparse.ArgumentParser(prog=prog, description=description)
parser.add_argument('infile', nargs='?',
type=argparse.FileType(encoding="utf-8"),
type=pathtype,
help='a JSON file to be validated or pretty-printed',
default=sys.stdin)
parser.add_argument('outfile', nargs='?',
type=argparse.FileType('w', encoding="utf-8"),
type=pathtype,
help='write the output of infile to outfile',
default=sys.stdout)
parser.add_argument('--sort-keys', action='store_true', default=False,
Expand Down Expand Up @@ -58,12 +70,17 @@ def main():
dump_args['indent'] = None
dump_args['separators'] = ',', ':'

with options.infile as infile, options.outfile as outfile:
with options.infile.open(encoding='utf-8') as infile:
try:
if options.json_lines:
objs = (json.loads(line) for line in infile)
else:
objs = (json.load(infile), )
objs = (json.load(infile),)
except ValueError as e:
raise SystemExit(e)

with options.outfile.open('w', encoding='utf-8') as outfile:
try:
for obj in objs:
json.dump(obj, outfile, **dump_args)
outfile.write('\n')
Expand Down