]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
[3.13] gh-132631: Fix "I/O operation on closed file" when parsing JSON Lines file...
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Thu, 23 Apr 2026 19:30:13 +0000 (21:30 +0200)
committerGitHub <noreply@github.com>
Thu, 23 Apr 2026 19:30:13 +0000 (19:30 +0000)
Co-authored-by: Hugo van Kemenade <1324225+hugovk@users.noreply.github.com>
Co-authored-by: Brian Schubert <brianm.schubert@gmail.com>
Lib/json/tool.py
Lib/test/test_json/json_lines.jsonl [new file with mode: 0644]
Lib/test/test_json/test_tool.py
Misc/NEWS.d/next/Library/2025-04-17-15-26-35.gh-issue-132631.IDFZfb.rst [new file with mode: 0644]

index fdfc3372bcca02e6ae298c90b727bd127356fb0b..e132fc5890006049182031ad87d9328b5ff5d857 100644 (file)
@@ -63,7 +63,8 @@ def main():
             infile = open(options.infile, encoding='utf-8')
         try:
             if options.json_lines:
-                objs = (json.loads(line) for line in infile)
+                lines = infile.readlines()
+                objs = (json.loads(line) for line in lines)
             else:
                 objs = (json.load(infile),)
         finally:
diff --git a/Lib/test/test_json/json_lines.jsonl b/Lib/test/test_json/json_lines.jsonl
new file mode 100644 (file)
index 0000000..d2f2921
--- /dev/null
@@ -0,0 +1,2 @@
+{"ingredients":["frog", "water", "chocolate", "glucose"]}
+{"ingredients":["chocolate","steel bolts"]}
index 2b63810d53981e97fdc13d83942d5bfef719e0ff..231fdfd762665e4562973d5ada886e31abd4d82f 100644 (file)
@@ -1,4 +1,5 @@
 import errno
+import pathlib
 import os
 import sys
 import textwrap
@@ -6,7 +7,7 @@ import unittest
 import subprocess
 
 from test import support
-from test.support import os_helper
+from test.support import force_not_colorized, os_helper
 from test.support.script_helper import assert_python_ok
 
 
@@ -147,6 +148,14 @@ class TestTool(unittest.TestCase):
         self.assertEqual(process.stdout, self.jsonlines_expect)
         self.assertEqual(process.stderr, '')
 
+    @force_not_colorized
+    def test_jsonlines_from_file(self):
+        jsonl = pathlib.Path(__file__).parent / 'json_lines.jsonl'
+        args = sys.executable, '-m', 'json.tool', '--json-lines', jsonl
+        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', 'json.tool', '-h')
         self.assertEqual(rc, 0)
diff --git a/Misc/NEWS.d/next/Library/2025-04-17-15-26-35.gh-issue-132631.IDFZfb.rst b/Misc/NEWS.d/next/Library/2025-04-17-15-26-35.gh-issue-132631.IDFZfb.rst
new file mode 100644 (file)
index 0000000..9cc1d5a
--- /dev/null
@@ -0,0 +1,2 @@
+Fix "I/O operation on closed file" when parsing JSON Lines file with
+:mod:`JSON CLI <json.tool>`.