Skip to content

Commit 42d645a

Browse files
gh-132631: Fix "I/O operation on closed file" when parsing JSON Lines file (#132632)
Co-authored-by: Brian Schubert <brianm.schubert@gmail.com>
1 parent 435be06 commit 42d645a

4 files changed

Lines changed: 15 additions & 1 deletion

File tree

Lib/json/tool.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -89,7 +89,8 @@ def main():
8989
infile = open(options.infile, encoding='utf-8')
9090
try:
9191
if options.json_lines:
92-
objs = (json.loads(line) for line in infile)
92+
lines = infile.readlines()
93+
objs = (json.loads(line) for line in lines)
9394
else:
9495
objs = (json.load(infile),)
9596
finally:
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
{"ingredients":["frog", "water", "chocolate", "glucose"]}
2+
{"ingredients":["chocolate","steel bolts"]}

Lib/test/test_json/test_tool.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import errno
2+
import pathlib
23
import os
34
import sys
45
import textwrap
@@ -157,6 +158,14 @@ def test_jsonlines(self):
157158
self.assertEqual(process.stdout, self.jsonlines_expect)
158159
self.assertEqual(process.stderr, '')
159160

161+
@force_not_colorized
162+
def test_jsonlines_from_file(self):
163+
jsonl = pathlib.Path(__file__).parent / 'json_lines.jsonl'
164+
args = sys.executable, '-m', self.module, '--json-lines', jsonl
165+
process = subprocess.run(args, capture_output=True, text=True, check=True)
166+
self.assertEqual(process.stdout, self.jsonlines_expect)
167+
self.assertEqual(process.stderr, '')
168+
160169
def test_help_flag(self):
161170
rc, out, err = assert_python_ok('-m', self.module, '-h',
162171
PYTHON_COLORS='0')
Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
Fix "I/O operation on closed file" when parsing JSON Lines file with
2+
:mod:`JSON CLI <json.tool>`.

0 commit comments

Comments
 (0)