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.
Code
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
CSV to JSON ConverterConvert comma-separated values into a JSON array of objects using the first row as field names, with support for quoted and escaped fields.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON Diff ViewerCompare two JSON documents and list every added, removed, and changed path in a structural diff, with clear before and after values.
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.