Sub topic 12
Processing large files with JSON Lines and row-by-row iteration
This chapter assumes you can open files with with, use json.loads and json.dumps, and read CSV with csv.reader and DictReader. It also assumes you know how functions and exceptions work.
Why whole-file loading breaks down
json.load reads the entire document and builds every Python object before it returns. A 2 GB JSON array can need several times that much memory, because Python objects carry overhead. A single JSON array also cannot be parsed until its closing bracket arrives, so you cannot start work on the first record early.
Two formats avoid this problem:
- CSV is already line-oriented.
csv.readerandDictReaderyield one row at a time. - JSON Lines (also called NDJSON) stores one complete JSON value per line. The usual extension is
.jsonl.
Writing and reading JSON Lines
To write, serialize each record with json.dumps and add a newline. json.dumps escapes newlines inside strings as \n, so a record never spans two lines, provided you do not pass indent.
To read, iterate over the file object. A file is a lazy iterator of lines, so only one line is in memory at a time.
import json
events = [{"id": 1, "type": "login"}, {"id": 2, "type": "logout"}]
with open("events.jsonl", "w", encoding="utf-8") as f:
for event in events:
f.write(json.dumps(event) + "\n")
with open("events.jsonl", encoding="utf-8") as f:
for line in f:
print(json.loads(line)["type"])Iterating CSV row by row
The CSV readers are also lazy. Looping over csv.DictReader fetches one row per iteration. The mistake to avoid is wrapping the reader in list(...), which loads every row at once.
import csv
total = 0
with open("items.csv", newline="", encoding="utf-8") as f:
for row in csv.DictReader(f):
total += int(row["qty"])
print(total)This keeps memory use flat. It holds one row and one running total, whatever the file size.
Combining reading and writing
Streaming works best when both ends stream. This function converts a CSV file to JSON Lines without holding more than one row in memory:
import csv
import json
def csv_to_jsonl(src, dst):
count = 0
with open(src, newline="", encoding="utf-8") as fin, \
open(dst, "w", encoding="utf-8") as fout:
for row in csv.DictReader(fin):
record = {"name": row["name"], "qty": int(row["qty"])}
fout.write(json.dumps(record) + "\n")
count += 1
return count
print(csv_to_jsonl("items.csv", "items.jsonl"))Compare this with the earlier CSV-to-JSON conversion, which built a full list and wrote one JSON array. That approach is simpler for small data. The streaming version trades a different output format for constant memory.
Common errors
- Blank lines. A trailing empty line makes
json.loads("")raiseJSONDecodeError. Skip lines that are empty afterstrip(). - One bad record. In a long file, one malformed line should not necessarily stop the job. Catch the error per line and record the line number.
- Using
indent. Pretty-printed output spans several lines and breaks the one-record-per-line rule. - Materializing the stream.
list(reader),f.read(), andf.readlines()all load everything. Use aforloop instead.
A tolerant reader handles the first two problems:
import json
def read_jsonl(path):
with open(path, encoding="utf-8") as f:
for number, line in enumerate(f, start=1):
line = line.strip()
if not line:
continue
try:
yield json.loads(line)
except json.JSONDecodeError as e:
print(f"line {number}: {e.msg}")
for record in read_jsonl("events.jsonl"):
print(record["id"])read_jsonl is a generator. It yields one record at a time, so callers can loop over it, filter it, or pass it to another generator without loading the file. The file stays open until the loop finishes or the generator is closed.
Choosing a format
| Situation | Better choice |
|---|---|
| Small config or API response | One JSON document |
| Large log or event stream | JSON Lines |
| Flat tabular data | CSV |
| Nested records at large scale | JSON Lines |
| Appending new records over time | JSON Lines or CSV |
JSON Lines suits appending: you open the file in "a" mode and write one more line, with no need to rewrite a closing bracket.
Exercise
A teammate loads a 3 GB CSV with rows = list(csv.DictReader(f)) and runs out of memory. What should they change, and what must they do differently with the data?
Show answer
Loop over the reader directly with for row in csv.DictReader(f): and process or write each row inside the loop. They cannot index into rows or loop over it twice, so any totals or output must be built during that single pass.
Exercise
Why does json.dumps(record, indent=2) break a JSON Lines file, and how do you fix it?
Show answer
With indent=2 the record spans several lines, but JSON Lines needs exactly one record per line. Call json.dumps(record) without indent and append "\n".