How to Find Broken Lines in a JSONL / NDJSON File (and Keep the Valid Ones)
Your .jsonl or .ndjson file won't load. Maybe it is a log file, a data export, or an AI training dataset, and somewhere in its million lines one record is broken. A normal JSON tool gives you one error and stops. This guide shows how to list every broken line with its line number, and how to save a clean file with only the valid records, online or with jq, Python and Node.js. Every command below was run on the example file, and the output shown is real.
The example file
Six lines, three of them broken. Save it as events.jsonl to follow along:
{"id":1,"event":"login","user":"ann"}
{"id":2,"event":"view","user":"ann"}
{"id":3,"event":
{"id":4,"event":"login","user":'bob'}
{"id":9007199254740993,"event":"logout","user":"ann"}- Line 3 was cut off, which happens when a program crashes while writing a log.
- Line 4 uses single quotes, which JSON does not allow.
- Line 5 is blank. JSON Lines does not allow empty lines between records.
- Line 6 is valid, but its ID is bigger than JavaScript can store exactly. Keep an eye on it; many tools quietly change it.
The fastest way: check the file in your browser
- Open the JSONL Viewer and drop the file on the page (or click Open file, or paste the text).
- Read the counters at the bottom. For the example: 6 total lines, 3 valid, 3 invalid.
- Click Invalid to list only the broken lines. Click a line to see exactly what is wrong:
Line 3, column 17: Unexpected end of input – expected a value
Line 4, column 32: Strings must use double quotes
Line 5, column 1: Blank line – JSON Lines does not allow empty lines between records- Click All (or type in the search box to narrow it down), then click Download matching valid records. You get a file with only the valid lines, in their original order, exactly as they were written.
The file never leaves your computer: it is read in pieces and checked in a background thread, with a progress bar and a Cancel button. In our tests, a 1 GB log with 4 million lines was checked in about 2.3 seconds in Chrome on a Mac, and a 2 GB file in about 4.3 seconds. Your browser needs roughly twice the file size in free memory.
Why a normal JSON tool gives the wrong answer
A JSON viewer or JSON.parse() expects one document. On a JSON Lines file it fails on line 2, even when line 2 is fine:
JSON.parse(text)
// SyntaxError: Unexpected non-whitespace character after JSON at position 38 (line 2 column 1)Plain jq reads JSON Lines correctly, but it stops at the first problem, and it can blame the wrong line:
$ jq -c . events.jsonl
{"id":1,"event":"login","user":"ann"}
{"id":2,"event":"view","user":"ann"}
jq: parse error: Invalid numeric literal at line 4, column 37The real problem starts on line 3. Because line 3 was cut off, jq keeps reading into line 4 to finish the record, then reports the error there. Lines 5 and 6 are never checked. The fix is to treat every line as its own document, which is what all the methods below do.
With jq: list every broken line
-R makes jq read each line as plain text, and fromjson parses it on its own, so one bad line cannot affect the next:
$ jq -R -r 'try (fromjson | empty) catch "line \(input_line_number): \(.)"' events.jsonl
line 3: Unfinished JSON term at EOF at line 1, column 16 (while parsing '{"id":3,"event":')
line 4: Invalid numeric literal at line 1, column 37 (while parsing '{"id":4,"event":"login","user":'bob'}')
line 5: Expected JSON value (while parsing '')Keep only the valid lines:
$ jq -R -c 'fromjson? // empty' events.jsonl > clean.jsonl
$ cat clean.jsonl
{"id":1,"event":"login","user":"ann"}
{"id":2,"event":"view","user":"ann"}
{"id":9007199254740993,"event":"logout","user":"ann"}9007199254740993 into 9007199254740992. Check your version with jq --version, or use one of the methods below, which copy each valid line unchanged.With Python: report and clean in one pass
This script reads one line at a time, so it works on files of any size with almost no memory. It prints each broken line with its number and writes the valid lines, unchanged, to a new file.
import json
import sys
src, out = sys.argv[1], sys.argv[2]
good = bad = 0
with open(src, encoding="utf-8-sig", newline="") as f, open(out, "w", encoding="utf-8", newline="\n") as w:
for n, line in enumerate(f, 1):
line = line.rstrip("\n").rstrip("\r") # Unix and Windows line endings
if not line.strip():
print(f"line {n}: blank line")
bad += 1
continue
try:
json.loads(line)
except json.JSONDecodeError as e:
print(f"line {n}, column {e.colno}: {e.msg}")
bad += 1
continue
w.write(line + "\n") # original text, not json.dumps()
good += 1
print(f"{good} valid, {bad} invalid")$ python3 check_jsonl.py events.jsonl clean.jsonl
line 3, column 17: Expecting value
line 4, column 32: Expecting value
line 5: blank line
3 valid, 3 invalidutf-8-sig skips a byte order mark (BOM) if a Windows editor added one; otherwise the first line would fail. newline="" keeps the \r of Windows line endings so the script can remove it itself.
With Node.js: stream a big file
import { createReadStream, createWriteStream } from 'node:fs'
import { createInterface } from 'node:readline'
const [src, out] = process.argv.slice(2)
const lines = createInterface({ input: createReadStream(src), crlfDelay: Infinity })
const clean = createWriteStream(out)
let n = 0, good = 0, bad = 0
for await (const line of lines) {
n++
if (!line.trim()) { console.log(`line ${n}: blank line`); bad++; continue }
try {
JSON.parse(line)
} catch (e) {
console.log(`line ${n}: ${e.message}`); bad++; continue
}
clean.write(line + '\n') // original text, not JSON.stringify()
good++
}
clean.end()
console.log(`${good} valid, ${bad} invalid`)$ node check-jsonl.mjs events.jsonl clean.jsonl
line 3: Unexpected end of JSON input
line 4: Unexpected token ''', ..."n","user":'bob'}" is not valid JSON
line 5: blank line
3 valid, 3 invalidcrlfDelay: Infinity treats Windows \r\n as one line break, so files from Windows machines work too.
Don't let the clean-up change your IDs
JavaScript stores every number as a 64-bit float, so integers above 9,007,199,254,740,991 can't be stored exactly. If you parse a record and write it back, the ID changes without any warning:
$ node -e 'console.log(JSON.stringify(JSON.parse(`{"id":9007199254740993}`)))'
{"id":9007199254740992}Python's integers don't have this problem, but json.dumps() still changes spacing and key formatting. That is why all the scripts above only check each line with the parser, then write the original text. The JSONL Viewer works the same way: its export and its formatted view both use the original text, so IDs like Twitter/X post IDs or database keys stay exact.
Common causes of broken lines
| What you see | Usual cause | Fix |
|---|---|---|
| Last line (or a few lines) cut off | The program crashed or the disk filled up while writing | Drop the broken line; the rest of the file is fine |
Hundreds of "broken" lines with {, "key": value, } | Records were pretty-printed (indent=2) instead of written one per line | It's a JSON file, not JSON Lines: open it in the JSON Viewer, or re-export with compact output |
Single quotes, True/None | Lines written with Python's print(dict) instead of json.dumps() | Fix the writer; repair single lines with JSON Repair |
| Blank lines | Extra \n when appending, or files joined together | Remove them; a single newline at the very end of the file is fine |
| Only line 1 fails | A byte order mark (BOM) from a Windows editor | Save as "UTF-8" without BOM |
Commas at line ends, or [ and ] around the file | A JSON array was turned into lines by hand | Convert properly with jq -c '.[]' file.json |
\r\n) are not an error. All the methods above handle them, and so does the JSONL Viewer.Quick answers
Is a newline at the end of the file allowed?
Yes, and it is normal. It does not create an extra empty record. Only blank lines between records are a problem.
Can a line be a string, a number or null instead of an object?
Yes. Any JSON value counts as one valid line: "text", 42, [1,2], true, false and null. Most real files use objects, though.
Is JSONL the same as NDJSON?
Yes, for practical purposes: one JSON value per line. Read more in JSON Lines (NDJSON) explained.