TExcelTAD
Home › JSON › JSON Lines / NDJSON

JSON Lines / NDJSON

A regular JSON document holds exactly one value. That's a problem for data that grows over time — logs, events, sensor readings, exported database rows. To add one record to a JSON array, you would have to rewrite the closing ], and to read it, you'd have to load the whole file into memory.

JSON Lines (also called NDJSON, newline-delimited JSON) solves this with one simple rule: one complete JSON value per line.

text
{"ts": "2025-05-01T10:00:00Z", "level": "info", "msg": "server started"}
{"ts": "2025-05-01T10:00:03Z", "level": "warn", "msg": "slow query", "ms": 812}
{"ts": "2025-05-01T10:01:10Z", "level": "error", "msg": "db timeout"}

The rules

Rule Detail
One value per line Usually an object, but any JSON value is allowed
Lines end with \n \r\n is tolerated by most readers
No line breaks inside a value The value must be written minified
UTF-8 Same as JSON
File extension .jsonl (or .ndjson)
Media type application/jsonl or application/x-ndjson

It's not a valid JSON document

As a whole, a JSON Lines file is not JSON — a normal parser sees several values and stops:

json · try it yourself
{"id": 1, "name": "Pen"}
{"id": 2, "name": "Ink"}
Invalid JSON: Unexpected non-whitespace character after JSON at position 25 (line 2 column 1)

Each line, however, is valid JSON on its own:

json · try it yourself
{"id": 2, "name": "Ink"}
Valid JSON: object with 2 keys
{
  "id": 2,
  "name": "Ink"
}

Reading JSON Lines in JavaScript

Split on newlines, skip empty lines, and parse each line separately. A bad line affects only itself:

js · try it yourself
const jsonl = `{"ts": "2025-05-01T10:00:00Z", "level": "info", "msg": "server started"}
{"ts": "2025-05-01T10:00:03Z", "level": "warn", "msg": "slow query", "ms": 812}
{"ts": "2025-05-01T10:00:09Z", "level": "info", "msg": "user login"
{"ts": "2025-05-01T10:01:10Z", "level": "error", "msg": "db timeout"}
`;

const records = [];
jsonl.split("\n").forEach((line, i) => {
  if (!line.trim()) return;                      // ignore blank lines
  try {
    records.push(JSON.parse(line));
  } catch {
    console.log(`line ${i + 1}: skipped (invalid JSON)`);
  }
});

console.log(records.length, "records");
for (const r of records.filter((r) => r.level !== "info")) {
  console.log(r.level.toUpperCase(), r.msg);
}
line 3: skipped (invalid JSON)
3 records
WARN slow query
ERROR db timeout

Notice how the broken third line (missing }) didn't ruin the rest of the file. With a single big JSON array, one error makes the entire file unreadable.

Writing JSON Lines

Stringify each record without indentation and join with \n. Appending a new record is just appending one more line:

js · try it yourself
const events = [
  { user: "an", action: "login" },
  { user: "binh", action: "upload", file: "report.pdf" },
];

let log = events.map((e) => JSON.stringify(e)).join("\n") + "\n";
log += JSON.stringify({ user: "an", action: "logout" }) + "\n";   // append

console.log(log.trimEnd());
console.log(log.split("\n").filter(Boolean).length, "lines");
{"user":"an","action":"login"}
{"user":"binh","action":"upload","file":"report.pdf"}
{"user":"an","action":"logout"}
3 lines

Warning: Never pretty print a JSON Lines record. JSON.stringify(obj, null, 2) adds line breaks, which would split one record across several lines.

Reading JSON Lines in Python

Files in Python iterate line by line, which makes JSON Lines very natural — even huge files can be processed one record at a time:

python · try it yourself
import json
import io

# io.StringIO stands in for open("events.jsonl", encoding="utf-8")
f = io.StringIO('''{"product": "tea", "qty": 2, "price": 4.5}
{"product": "cup", "qty": 1, "price": 3.0}
{"product": "tea", "qty": 1, "price": 4.5}
''')

totals = {}
for line in f:
    if line.strip():
        row = json.loads(line)
        totals[row["product"]] = totals.get(row["product"], 0) + row["qty"] * row["price"]

for product, amount in sorted(totals.items()):
    print(f"{product}: {amount:.2f}")

out = io.StringIO()
for product, amount in sorted(totals.items()):
    out.write(json.dumps({"product": product, "total": amount}) + "\n")
print(out.getvalue(), end="")
cup: 3.00
tea: 13.50
{"product": "cup", "total": 3.0}
{"product": "tea", "total": 13.5}

Where you'll meet JSON Lines

  • Structured logging — many logging libraries emit one JSON object per line.
  • Data pipelines and big data tools — BigQuery, Spark and many warehouses import/export .jsonl.
  • Machine learning datasets — training examples, one per line.
  • Streaming APIs — servers send application/x-ndjson and the client handles each line as it arrives.
  • Command-line tools — jq -c outputs one value per line, perfect for piping.

JSON array vs JSON Lines

JSON array file JSON Lines file
Append a record Rewrite the end of the file Append one line
Read huge files Must load everything One line at a time
One corrupt record Whole file unreadable Only that line lost
Pretty printing Possible Not possible
Valid JSON document Yes No (each line is)

Test yourself

What is the main rule of JSON Lines?

  1. Every key on its own line
  2. One complete JSON value per line
  3. Lines must start with a comma
  4. The whole file is one array

Why can't you pretty print records in a JSON Lines file?

  1. It would make the file too big
  2. Line breaks would split a record across lines
  3. JSON Lines forbids spaces
  4. Indentation is invalid JSON

Which file extension is commonly used for JSON Lines?

  1. .jsn
  2. .json5
  3. .jsonl
  4. .jsx