Skip to content
Open
Show file tree
Hide file tree
Changes from 2 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
2 changes: 1 addition & 1 deletion Lib/json/tool.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@ def main():
infile = open(options.infile, encoding='utf-8')
try:
if options.json_lines:
objs = (json.loads(line) for line in infile)
objs = tuple(json.loads(line) for line in infile)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This has significant memory implications for large .jsonl files. It might be better to instead move the finally clause either to the outer try or just after the with outfile block, but that does have implications for the infile == outfile case.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hmm, yeah, moving it gives a blank file when infile == outfile...

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Or we could load all the lines into a list. This uses more memory than before, but less than the tuple as we're only deserialising each line when consumed from the generator:

Suggested change
objs = tuple(json.loads(line) for line in infile)
lines = infile.readlines()
objs = (json.loads(line) for line in lines)

I don't think it's worth adding much extra complexity for this CLI, as if someone needs to process extremely large .jsonl files they can write their own code to do exactly what they need.

else:
objs = (json.load(infile),)
finally:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
Fix "I/O operation on closed file" when parsing JSON Lines file with JSON
CLI.
Loading