diff --git a/Lib/json/tool.py b/Lib/json/tool.py index 050c2fe2161e3e..7f17e949f00a96 100644 --- a/Lib/json/tool.py +++ b/Lib/json/tool.py @@ -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: @@ -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) diff --git a/Lib/test/test_json/test_tool.py b/Lib/test/test_json/test_tool.py index 30f9bb3331605c..f49e98c857fe11 100644 --- a/Lib/test/test_json/test_tool.py +++ b/Lib/test/test_json/test_tool.py @@ -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')