Parse JSON Lines Records Incrementally
An incremental JSON Lines reader that yields parsed records line by line with strict validation and clear errors for malformed input.
Code
export async function* parseJsonLines(source, validate) {
let buffer = "";
let lineNo = 0;
for await (const chunk of source) {
buffer += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
let nl;
while ((nl = buffer.indexOf("\n")) !== -1) {
const raw = buffer.slice(0, nl).replace(/\r$/, "");
buffer = buffer.slice(nl + 1);
lineNo += 1;
if (raw.trim() === "") continue;
let record;
try {
record = JSON.parse(raw);
} catch (err) {
throw new Error(`invalid JSON on line ${lineNo}: ${err.message}`);
}
if (validate) {
const problem = validate(record);
if (problem) throw new Error(`record failed validation on line ${lineNo}: ${problem}`);
}
yield { line: lineNo, record };
}
}
if (buffer.trim() !== "") {
lineNo += 1;
let record;
try {
record = JSON.parse(buffer);
} catch (err) {
throw new Error(`invalid JSON on line ${lineNo}: ${err.message}`);
}
if (validate) {
const problem = validate(record);
if (problem) throw new Error(`record failed validation on line ${lineNo}: ${problem}`);
}
yield { line: lineNo, record };
}
}Parsing a whole multi-gigabyte JSONL file with JSON.parse exhausts memory before any record is usable.
Use case: engineers processing logs or exports larger than memory
Inputs / outputs
- Input: a readable stream or async iterable of string chunks, optional per-record validator
- Output: async generator yielding parsed records with their line numbers
Error conditions
- line is not valid JSON
- record fails the supplied validator
- blank line inside data
Approach
accumulate chunks, split on newline boundaries, parse each complete line immediately, keep only the partial tail in memory.
Implementation
export async function* parseJsonLines(source, validate) {
let buffer = "";
let lineNo = 0;
for await (const chunk of source) {
buffer += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
let nl;
while ((nl = buffer.indexOf("\n")) !== -1) {
const raw = buffer.slice(0, nl).replace(/\r$/, "");
buffer = buffer.slice(nl + 1);
lineNo += 1;
if (raw.trim() === "") continue;
let record;
try {
record = JSON.parse(raw);
} catch (err) {
throw new Error(`invalid JSON on line ${lineNo}: ${err.message}`);
}
if (validate) {
const problem = validate(record);
if (problem) throw new Error(`record failed validation on line ${lineNo}: ${problem}`);
}
yield { line: lineNo, record };
}
}
if (buffer.trim() !== "") {
lineNo += 1;
let record;
try {
record = JSON.parse(buffer);
} catch (err) {
throw new Error(`invalid JSON on line ${lineNo}: ${err.message}`);
}
if (validate) {
const problem = validate(record);
if (problem) throw new Error(`record failed validation on line ${lineNo}: ${problem}`);
}
yield { line: lineNo, record };
}
}
Verification tests
import { test } from "node:test";
import assert from "node:assert/strict";
import { parseJsonLines } from "./example.mjs";
async function* fromString(s) { yield s; }
test("yields each record with its line number", async () => {
const out = [];
for await (const item of parseJsonLines(fromString('{"a":1}\n{"a":2}\n{"a":3}\n'))) {
out.push(item);
}
assert.deepEqual(out, [
{ line: 1, record: { a: 1 } },
{ line: 2, record: { a: 2 } },
{ line: 3, record: { a: 3 } },
]);
});
test("rejects malformed JSON with the line number", async () => {
await assert.rejects(
(async () => {
for await (const _ of parseJsonLines(fromString('{"a":1}\nnot json\n'))) { /* drain */ }
})(),
/invalid JSON on line 2/,
);
});
test("applies the per-record validator", async () => {
const validate = (r) => (typeof r.id === "number" ? null : "id must be a number");
await assert.rejects(
(async () => {
for await (const _ of parseJsonLines(fromString('{"id":1}\n{"id":"x"}\n'), validate)) { /* drain */ }
})(),
/record failed validation on line 2/,
);
});
Dependencies and running
No external dependencies (standard library only).
Runtime: node >= 18 Entry point: node example.mjs
Limitations and error handling
no multi-line record support; no gzip handling.
Verification boundary
execution tests ran offline in an isolated temp dir with a sanitized environment; no network, no writes outside the sandbox
Interactive Tools for This Topic
Report a problem with this exampleOpens a pre-filled issue on GitHub.