Parse Newline-Delimited JSON Streams

Decode newline-delimited JSON records from a file or socket one line at a time, reporting the offending line when a record fails to parse.

PythonData Integrity

Code

pythonsnippet
21 lines
import io
import json
from typing import Any, Iterator


def iter_json_lines(stream: io.TextIOBase) -> Iterator[Any]:
    for line_number, raw in enumerate(stream, start=1):
        text = raw.strip()
        if not text:
            continue
        try:
            yield json.loads(text)
        except json.JSONDecodeError as error:
            raise ValueError(
                f"invalid JSON on line {line_number}: {error.msg}"
            ) from error


payload = io.StringIO('{"id": 1}\n{"id": 2}\n')
records = list(iter_json_lines(payload))
print(len(records))

What the code does

Parse Newline-Delimited JSON Streams keeps everything in the function iter_json_lines.

Repetition is confined to for line_number, raw in enumerate(stream, start=1) — the rest of the file is straight-line. A ValueError is raised inside an except block, so it is conditional on that failure being handled in the first place.

Using it

The primary signature is def iter_json_lines(stream: io.TextIOBase) -> Iterator[Any]

The surface worth importing is iter_json_lines; the helpers around it are private to the snippet.

Key statements

except json.JSONDecodeError as error:
    raise ValueError(
        f"invalid JSON on line {line_number}: {error.msg}"
    ) from error

Interactive Tools for This Topic

FAQ

When is the exception raised?
Inside an `except` handler — the `ValueError` fires only while that failure type is already being handled, not on its own trigger.
Anything to download besides the language toolchain?
Nothing beyond the toolchain you already have for this language. Every import resolves inside the standard library — `io`, `json`, `typing`. The file defines `iter_json_lines` at load time.