JSON Lines (NDJSON) Explained: Read, Write and Convert
JSON Lines (also called NDJSON, newline-delimited JSON, with the extensions .jsonl or .ndjson) is a simple format: one complete JSON value per line. It is everywhere in logs, data exports, BigQuery and Elasticsearch imports, and AI datasets and fine-tuning files. Here is why it exists, how to read and write it, and how to convert it to and from regular JSON. All commands below were run with real output.
What it looks like
A regular JSON array:
[{"id":1,"type":"signup","user":"ann"},{"id":2,"type":"login","user":"bob"},{"id":3,"type":"login","user":"ann"}]The same data as JSON Lines:
{"id":1,"type":"signup","user":"ann"}
{"id":2,"type":"login","user":"bob"}
{"id":3,"type":"login","user":"ann"}The rules are short:
- Each line is one valid JSON value (almost always an object), written on a single line.
- Lines are separated by
\n. There are no commas between lines and no surrounding[ ]. - UTF-8 encoding.
Why use it instead of a JSON array?
- Streaming: you can process a 50 GB file one line at a time with almost no memory. A JSON array has to be parsed as a whole (or with a special streaming parser).
- Appending: adding a record is just writing one more line – perfect for logs. With an array you would have to rewrite the closing
]. - Robustness: one corrupt line doesn’t make the whole file unreadable.
- Unix tools work:
wc -lcounts records,head,tail -f,grepandsplitall just work.
The trade-off: it’s not one JSON document, so a normal JSON parser rejects it, and humans find a single pretty-printed array easier to read.
The errors you get when you parse it as normal JSON
// JavaScript
JSON.parse(text)
// SyntaxError: Unexpected non-whitespace character after JSON at position 9 (line 2 column 1)
# Python
json.load(f)
# json.decoder.JSONDecodeError: Extra data: line 2 column 1 (char 9)Both mean the same thing: the parser read one complete value and then found more. If you see them, the file is JSON Lines (or several JSON documents stuck together) – parse it line by line instead. To see which lines of a file are broken, open it in the JSONL Viewer: it checks every line on its own and lists the bad ones with the exact column.
Convert with jq
# JSON array → JSON Lines
$ jq -c '.[]' events.json > events.jsonl
# JSON Lines → JSON array (-s = slurp all lines into one array)
$ jq -s '.' events.jsonl > events.json
# filter lines
$ jq -c 'select(.type == "login")' events.jsonl
{"id":2,"type":"login","user":"bob"}
{"id":3,"type":"login","user":"ann"}
# count records and append one
$ wc -l < events.jsonl
3
$ echo '{"id":4,"type":"logout","user":"ann"}' >> events.jsonlMore filters like these are in the jq cheat sheet.
Python
import json
# read – one line at a time, constant memory
with open("events.jsonl", encoding="utf-8") as f:
for line_no, line in enumerate(f, 1):
if not line.strip():
continue # tolerate blank lines
event = json.loads(line)
if event["type"] == "login":
print(line_no, event["user"])
# write
with open("out.jsonl", "w", encoding="utf-8") as f:
for row in rows:
f.write(json.dumps(row, ensure_ascii=False) + "\n")line_no: when json.loads fails on line 48,213 of a big export, you can jump straight to the broken record.With pandas:
import pandas as pd
df = pd.read_json("events.jsonl", lines=True)
df.to_json("out.jsonl", orient="records", lines=True, force_ascii=False)
# huge files: read in chunks
for chunk in pd.read_json("events.jsonl", lines=True, chunksize=100_000):
process(chunk)Node.js (streaming)
import { createReadStream } from 'node:fs'
import { createInterface } from 'node:readline'
const lines = createInterface({ input: createReadStream('events.jsonl'), crlfDelay: Infinity })
let count = 0
for await (const line of lines) {
if (!line.trim()) continue
const event = JSON.parse(line)
if (event.user === 'ann') count++
}
console.log('events by ann:', count)crlfDelay: Infinity makes Windows line endings (\r\n) count as one line break. To write JSON Lines, call stream.write(JSON.stringify(obj) + '\n') for each record.
Common mistakes
- Pretty-printing each record.
json.dumps(row, indent=2)spreads one record over many lines and breaks the format. Always write compact JSON per line. - Adding commas at the ends of lines, or
[and]around the file. - A byte order mark (BOM) at the start of the file, added by some Windows editors – the first line then fails to parse. Save as UTF-8 without BOM.
- Unescaped newlines in strings –
JSON.stringifyandjson.dumpsescape them correctly, so always use a serializer instead of building lines by hand.
Inspect a file and find broken lines
Long single-line records are hard to read, and one bad line in a 2 GB export is hard to find. Open the file in the JSONL Viewer: it reads the file in pieces, checks each line, and shows how many lines are valid and invalid. Filter to the invalid lines to see each error with its line number and column, click a valid line to see it pretty-printed, and download only the valid records that match your search. Big IDs like 9007199254740993 are kept exactly as written, and nothing leaves your browser.
For one record, you can also paste the line into the JSON Formatter. To do the same from the command line, see how to find broken lines in a JSONL file.