Skip to content
Raisalon

Software Engineering

Python JSONDecodeError: fix “Extra data” in JSON Lines files

Diagnose Python’s Extra data error by inspecting the second value. Read JSON Lines one record at a time and report the exact line when a record is malformed.

Author
3 min read

Python’s JSON decoder reports Extra data when it finishes reading one valid value and finds more non-whitespace text after it. Two valid JSON objects can produce an invalid JSON document. Before repairing the file, establish whether the producer meant to write a single document, one record per line, or a response with unexpected text appended.

Locate the first character after the valid value

This example contains two objects separated by a newline. Each object by itself is valid. Asking json.loads to parse the entire string requires it to interpret both as one value.

import json

payload = '{"id": 11}\n{"id": 12}\n'
try:
    json.loads(payload)
except json.JSONDecodeError as exc:
    print(exc.msg, exc.lineno, exc.colno)  # Extra data 2 1
    print(repr(payload[exc.pos:exc.pos + 12]))

The offset points to the opening brace of the second object. Reformatting the first object, changing indentation or removing the final newline won’t resolve the inconsistency. The decoder already understood the first value. In a real incident inspect a short, non-sensitive slice around the offset. A second opening brace, a status message and an HTML fragment all suggest different upstream causes. Python JSON decoder documentation

Choose the parser from the file contract

Format Example layout How to consume it
One JSON document An object, or an array containing several objects Use json.load(file) once.
JSON Lines, often named JSONL or NDJSON One complete JSON value per physical line Decode each line independently.
Adjacent objects without a separator {"id":11}{"id":12} Check the producer’s framing contract. This is neither one document nor two JSON Lines records.

A regular JSON document may span many lines. Calling json.loads on every line of a pretty-printed array breaks its opening bracket, fields and closing bracket into meaningless pieces. Conversely, wrapping an entire JSON Lines export in square brackets without inserting separators produces an invalid array. Inspect a few complete records and confirm the export format before changing a reader. JSON Lines format

Stream records and keep the original line number

Here is a runnable object-record reader. It accepts a text stream so that the same function works with a file or an in-memory fixture. JSON Lines permits any JSON value, including null. This application adds its own narrower contract that every event must be an object. It distinguishes an invalid JSON line from a valid value of the wrong type.

import io
import json

def read_events(stream):
    for number, line in enumerate(stream, start=1):
        try:
            value = json.loads(line)
        except json.JSONDecodeError as exc:
            raise ValueError(
                f"Line {number}, column {exc.colno}: {exc.msg}"
            ) from exc
        if not isinstance(value, dict):
            raise ValueError(f"Line {number}: expected an event object")
        yield value

sample = io.StringIO('{"id":11}\n{"id":12}\n')
print([event["id"] for event in read_events(sample)])  # [11, 12]

For a real file, open it with encoding="utf-8" and pass the handle to read_events. Process each yielded record before reading the next if you want to bound memory by the size of an individual record. The list in the example exists only to make the result easy to check. An enormous individual line can still use significant memory.

A trailing newline after the last value is fine. A separate blank line between values has no JSON value at all. Let the reader report that line unless the export contract explicitly permits blank separators. If your application elects to skip blanks, keep the original line numbering so the operator can still find a failed record in the source file.

Fix repeated writes at the producer

A common source of this error is a loop that calls json.dump repeatedly on the same file. JSON provides no automatic separator between calls. For a line-oriented export, serialize each event to one compact line and add the newline explicitly. A newline inside a string field is escaped by the encoder, so the record can still occupy one physical line.

import io
import json

output = io.StringIO()
for event in [{"id": 11, "note": "one\ntwo"}, {"id": 12}]:
    output.write(json.dumps(event, ensure_ascii=False) + "\n")
assert len(output.getvalue().splitlines()) == 2

For a client expecting a single array, use an array document instead and contract-test the whole response. If the unexpected bytes are a footer or debug log, fix the writer that mixed diagnostics into the data stream. Parsing the first value and discarding the remainder would silently lose records in the two-object case.

Next steps

Keep a two-record fixture, a malformed second record and a valid string containing an escaped newline. Check both the decoded IDs and the failure’s line number. To inspect an individual sanitized record, paste just that record into the JSON formatter. If the first byte of a web response is an angle bracket, use the fetch response diagnosis to find out which page the server sent.

Share

Written by