Skip to content
Open
Show file tree
Hide file tree
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: 13 additions & 12 deletions Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,23 +84,23 @@ def main():

try:
if options.infile == '-':
infile = sys.stdin
in_f = sys.stdin.fileno()
else:
infile = open(options.infile, encoding='utf-8')
try:
in_f = options.infile

if options.outfile is None:
out_f = sys.stdout.fileno()
else:
out_f = options.outfile

with (open(in_f, 'r', encoding='utf-8') as infile,
open(out_f, 'w', encoding='utf-8') as outfile):

if options.json_lines:
objs = (json.loads(line) for line in infile)
else:
objs = (json.load(infile),)
finally:
if infile is not sys.stdin:
infile.close()
objs = [json.load(infile)]

if options.outfile is None:
outfile = sys.stdout
else:
outfile = open(options.outfile, 'w', encoding='utf-8')
with outfile:
if can_colorize(file=outfile):
t = get_theme(tty_file=outfile).syntax
for obj in objs:
Expand All @@ -111,6 +111,7 @@ def main():
for obj in objs:
json.dump(obj, outfile, **dump_args)
outfile.write('\n')

except ValueError as e:
raise SystemExit(e)

Expand Down
8 changes: 8 additions & 0 deletions Lib/test/test_json/test_tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,14 @@ def test_jsonlines(self):
self.assertEqual(process.stdout, self.jsonlines_expect)
self.assertEqual(process.stderr, '')

@force_not_colorized
def test_jsonlines_with_file(self):
infile = self._create_infile(self.jsonlines_raw)
args = sys.executable, '-m', self.module, '--json-lines', infile
process = subprocess.run(args, capture_output=True, text=True, check=True)
self.assertEqual(process.stdout, self.jsonlines_expect)
self.assertEqual(process.stderr, '')

def test_help_flag(self):
rc, out, err = assert_python_ok('-m', self.module, '-h',
PYTHON_COLORS='0')
Expand Down
Loading