Files and data
Parse newline-delimited JSON records
For small newline-delimited JSON input, parse each nonempty record line separately and attach the line number to errors. Each line is an independent JSON value, unlike one large JSON array.
Worked example
Node.js example · save as example.mjs and run node example.mjs
const text = '{"id":1}\n{"id":2}\n';
const rows = text.split(/\r?\n/);
const values = [];
for (let i = 0; i < rows.length; i++) {
if (i === rows.length - 1 && rows[i] === "") continue;
try { values.push(JSON.parse(rows[i])); }
catch { throw new Error(`Invalid JSON at line ${i + 1}`); }
}
console.log(values.map(row => row.id).join(","));How it works
The example allows the final terminator without treating it as an extra record. Interior blank lines are not silently discarded. Reporting the line number helps locate a bad export record without pretending that the entire file is one JSON document.
Limits and mistakes
This version keeps the full text and parsed values in memory. For large files, combine a line reader with per-record processing and bounded storage. Validate every parsed record against the expected schema.
Check the result
Expect 1,2. Insert malformed JSON on line two and confirm the diagnostic identifies that line. Test an interior blank line under your chosen format policy.
Sources
Reference documentation for the behavior used in this guide: