Read JSONL Records Line by Line

Iterate JSON Lines files lazily, skip blank lines, report malformed records with line numbers, and cap record size to avoid memory spikes.

PythonData Integrity

Code

pythonsnippet
63 lines
import json
import tempfile
from collections.abc import Iterator
from pathlib import Path
from typing import Any


class JsonlError(RuntimeError):
    def __init__(self, line_no: int, message: str) -> None:
        super().__init__(f"line {line_no}: {message}")
        self.line_no = line_no


def read_jsonl(
    path: Path,
    *,
    max_record_bytes: int = 64 * 1024,
) -> Iterator[dict[str, Any]]:
    if max_record_bytes < 2:
        raise ValueError("max_record_bytes must be at least 2")
    with path.open("r", encoding="utf-8") as handle:
        for line_no, raw in enumerate(handle, start=1):
            size = len(raw.encode("utf-8"))
            if size > max_record_bytes:
                raise JsonlError(
                    line_no,
                    f"record is {size} bytes, limit is {max_record_bytes}",
                )
            line = raw.strip()
            if not line:
                continue
            try:
                record = json.loads(line)
            except json.JSONDecodeError as error:
                raise JsonlError(line_no, f"invalid JSON: {error.msg}") from error
            if not isinstance(record, dict):
                raise JsonlError(line_no, "record must be a JSON object")
            yield record


def main() -> None:
    with tempfile.TemporaryDirectory() as tmp:
        path = Path(tmp) / "events.jsonl"
        path.write_text(
            '{"id": 1, "kind": "click"}\n'
            "\n"
            '{"id": 2, "kind": "view"}\n'
            '{"id": 3, "kind": }\n'
            '{"id": 4, "kind": "buy"}\n',
            encoding="utf-8",
        )
        good = 0
        try:
            for record in read_jsonl(path):
                good += 1
                print("record", record["id"])
        except JsonlError as error:
            print(f"stopped after {good} records: {error}")


if __name__ == "__main__":
    main()

Inside the snippet

Read JSONL Records Line by Line is built around the class JsonlError and the functions __init__, read_jsonl and main.

Iteration happens inside for line_no, raw in enumerate(handle, start=1) — everything outside it runs once. Iterator, Path, Any are the only symbols borrowed from tempfile — the coupling is explicit and narrow. ValueError and JsonlError appears at a raise inside an except handler — it fires only while that failure type is already being handled.

What to watch for

  • Dependency check: tempfile — not built-in, must be present in the project.
  • The guard max_record_bytes < 2 short-circuits the flow with an early raise when its condition holds.

Putting it to use

Signature: def read_jsonl( path: Path, *, max_record_bytes: int = 64 * 1024, ) -> Iterator[dict[str, Any]]

Running the file prints labeled results such as record, stopped after — each operation’s effect is visible in the output.

The demo flow inside main is read_jsonl — run the file to see it end to end.

Core lines

def __init__(self, line_no: int, message: str) -> None:
    super().__init__(f"line {line_no}: {message}")
    self.line_no = line_no
with tempfile.TemporaryDirectory() as tmp:
    path = Path(tmp) / "events.jsonl"
    path.write_text(
        '{"id": 1, "kind": "click"}\n'
        "\n"
        '{"id": 2, "kind": "view"}\n'
        '{"id": 3, "kind": }\n'
        '{"id": 4, "kind": "buy"}\n',
        encoding="utf-8",
    )
    good = 0
    try:
except json.JSONDecodeError as error:
    raise JsonlError(line_no, f"invalid JSON: {error.msg}") from error

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValueError` and `JsonlError` fires only while that failure type is already being handled, not on its own trigger.
What does Read JSONL Records Line by Line print when run?
Execute the whole file; each printed line is prefixed with a label like `record`, `stopped after`.