
A script writes two dictionaries without an error, but the next json.load() reports Extra data. I would check the file format before changing the reader. Two successful writes can produce two adjacent JSON documents, while the reader expects one. Adding a newline does not turn those documents into a single JSON array.
Reproduce the mismatch without touching a real file
import io
import json
buffer = io.StringIO()
json.dump({'id': 1}, buffer)
json.dump({'id': 2}, buffer)
print(buffer.getvalue()) # {"id": 1}{"id": 2}
try:
json.loads(buffer.getvalue())
except json.JSONDecodeError as exc:
print(exc.msg) # Extra dataPython documents that JSON is not a framed protocol. Repeated dump() calls on the same file do not add an enclosing container or a record separator. This fixture explains one cause of Extra data, not every possible cause: inspect the actual input before assuming the producer made the same mistake.
Use one array when the consumer expects one document
For a small export that another program loads as a collection, serialize the list once. This example uses exclusive creation mode, x, so it refuses to overwrite an existing demo file. Run it in a scratch folder with a fresh filename.
records = [{'id': 1}, {'id': 2}]
with open('records-demo.json', 'x', encoding='utf-8') as f:
json.dump(records, f, indent=2, allow_nan=False)
with open('records-demo.json', encoding='utf-8') as f:
restored = json.load(f)
print([row['id'] for row in restored]) # [1, 2]The array brackets belong to the document. Appending another object after the closing bracket breaks that format. For an existing small array, use an application-controlled read, modify and replacement workflow with backups as needed, rather than blindly opening it in append mode. A plain rewrite is not automatically crash-safe or safe against concurrent writers.
Use JSON Lines only when both ends agree
For independent records, JSON Lines defines one valid JSON value per physical line in UTF-8. It is a different contract, often named with a .jsonl extension. A normal single-document JSON reader is not a JSON Lines reader.
with open('records-demo.jsonl', 'x', encoding='utf-8') as f:
for row in records:
f.write(json.dumps(row, allow_nan=False) + chr(10))
with open('records-demo.jsonl', encoding='utf-8') as f:
for number, line in enumerate(f, start=1):
row = json.loads(line)
print(number, row['id']) # 1 1, then 2 2Do not pass indent for this writer: pretty-printing an object across several lines breaks the one-value-per-line layout. The serializer escapes a newline inside a string, so the string content need not create another physical record. Blank lines are not valid JSON Lines values; this reader fails on them instead of silently skipping them.
For a new append operation, the existing file must already follow the same format and end at a complete record boundary. Appending after a partial last record, or after a final record without a separating newline, can corrupt the stream. Multiple writers, interrupted writes, rotation and durability need a separate storage design. This short example does not solve those problems.
Verify the contract, not only the parser
I ran these small examples with Python 3.10.12. Adjacent objects raised Extra data; the array restored both IDs; the line reader returned two records. A string containing a newline stayed on one physical JSON Lines record. These are synthetic checks, not a production ingestion or recovery test.
The examples use allow_nan=False to reject non-finite float output. That does not validate field names, required keys or types. Confirm the expected container with the consumer, impose input-size limits for untrusted data, and report malformed records rather than silently dropping them. Choose the format first; then make the writer and reader match it.
Comments
Post a Comment