Python json.dump Is Not a Framed Protocol: Why Repeated Calls Produce Invalid JSON and How to Serialize Multiple LLM Responses Safely
Python's json module explicitly warns that JSON lacks framing, so calling dump() twice on the same file object writes two adjacent documents that json.load() cannot parse. The fix is to collect objects into a list and dump once, or use newline-delimited JSON with raw_decode for streaming scenarios.
On this page
The short answer
Repeated json.dump() calls on a single file-like object produce concatenated JSON documents with no separator, which is invalid as a single JSON document. The Python documentation states this directly: unlike pickle and marshal, JSON is not a framed protocol. The safe approaches are to accumulate all objects into a Python list and call dump() exactly once, producing a valid JSON array, or to write one JSON document per line (JSON Lines format) and parse them sequentially using JSONDecoder.raw_decode(), which is designed to decode a document from a string that may have extraneous data at the end.
JSON is not a framed protocol
The Python standard library documentation for the json module contains an explicit warning under the dump() function: unlike pickle and marshal, JSON is not a framed protocol, so trying to serialize multiple objects with repeated calls to dump() using the same fp will result in an invalid JSON file. This is not an implementation quirk. JSON as specified by RFC 7159 defines a single top-level value per document. There is no built-in delimiter, length prefix, or end-of-record marker that would let a parser know where one document stops and the next begins. The format simply does not carry that information in its grammar.
Practical tip
When building an LLM pipeline that writes conversation turns incrementally, prefer JSON Lines: open the file in append mode, call json.dumps() once per turn, write the result followed by a newline, and read back line by line. This avoids loading the entire conversation into memory and lets you recover partial output after a crash.
What repeated dump() calls actually produce
When you call json.dump(obj1, fp) followed by json.dump(obj2, fp) on the same file object, the first call writes a complete JSON document (for example, a JSON object enclosed in curly braces) and the second call immediately writes another complete JSON document right after it, with no whitespace, no separator, and no wrapper array. The resulting byte sequence looks like {"a":1}{"b":2}. If you then pass that file to json.load(), the parser reads the first object, encounters the opening brace of the second object, and raises a JSONDecodeError with the message Extra data. The file is not corrupt in the sense that bytes were lost; it is syntactically invalid as a single JSON document because two top-level values appear where the grammar permits only one.
Why LLM response serialization hits this pattern
Developers working with large language models often need to persist multiple completions, conversation turns, or batch results to a single file. A natural but incorrect instinct is to open a file once and loop over the responses, calling json.dump() inside the loop. This pattern is especially common when responses arrive incrementally from a streaming API and the developer wants to write each chunk as soon as it is available. The result is a file that looks like valid JSON in a text editor but cannot be loaded programmatically. The problem is not specific to LLM work; it occurs whenever a developer treats json.dump() as though it appends records to a container, which it does not.
The fix: collect then serialize once
The simplest correct approach is to accumulate all response dictionaries into a Python list and call json.dump() exactly once on that list. The list serializes to a JSON array, which is a single valid JSON document containing multiple objects. This requires that all responses fit in memory at the time of serialization, which is acceptable for most conversation logs and batch completions. If memory is a concern, the JSON Lines approach described in the next section is preferable. The key principle is that one file should contain exactly one top-level JSON value.
Alternative: newline-delimited JSON for streaming
When responses arrive incrementally and you cannot hold the full list in memory, write one JSON document per line and separate them with a newline character. Each line is independently parseable. To read such a file back, use the JSONDecoder.raw_decode() method, which the documentation describes as decoding a JSON document from a string beginning with a JSON document and returning a two-tuple of the Python representation and the index where the document ended. This is explicitly designed for strings that may have extraneous data at the end, making it suitable for parsing concatenated documents line by line. The format is commonly called JSON Lines or NDJSON and is supported by many log-processing tools.
Trade-off between array and JSON Lines
A single JSON array loaded with json.loads() gives you the entire collection in one call and supports direct indexing. It requires the whole file in memory and fails entirely if any single line is malformed. JSON Lines allows incremental reading, partial recovery after a crash, and streaming writes without holding all data in memory, but it cannot be validated as a single document without a schema applied per line, and standard json.load() will not parse it. For LLM pipelines where each turn is independent and the conversation may be very long, JSON Lines is often the more robust choice. For small batch results that will always be loaded together, a single array is simpler.
Concrete illustration
The following example uses Python 3.8 or later with only the standard library. It first demonstrates the broken pattern where two dump calls produce a string that json.loads() rejects, then shows the corrected pattern where a list is dumped once and parses successfully. The StringIO objects make the output visible without touching the filesystem.
import json
from io import StringIO
# BROKEN: two dump calls on the same file object
fp = StringIO()
json.dump({"role": "assistant", "content": "Hello"}, fp)
json.dump({"role": "assistant", "content": "World"}, fp)
result = fp.getvalue()
print(repr(result))
# Output: '{"role": "assistant", "content": "Hello"}{"role": "assistant", "content": "World"}'
try:
json.loads(result)
except json.JSONDecodeError as e:
print(f"JSONDecodeError: {e}")
# Output: JSONDecodeError: Extra data: line 1 column 42 (char 41)
# FIXED: collect then dump once
fp2 = StringIO()
responses = [
{"role": "assistant", "content": "Hello"},
{"role": "assistant", "content": "World"},
]
json.dump(responses, fp2)
valid = fp2.getvalue()
print(repr(valid))
# Output: '[{"role": "assistant", "content": "Hello"}, {"role": "assistant", "content": "World"}]'
parsed = json.loads(valid)
print(len(parsed))
# Output: 2Applicability limits and schema enforcement
This framing issue applies to any multi-object serialization, not only LLM responses. Any time you need to store a collection of JSON documents in one file, you must choose a strategy: wrap in an array, use JSON Lines, or adopt a length-prefixed protocol outside the scope of the json module. For production pipelines, define a JSON Schema that constrains each object's required properties. The JSON Schema specification states that required properties are those that must be present in a valid instance; a property with value null is not equivalent to the property being absent. Applying a per-item schema to each element of your array or each line of your JSON Lines file lets downstream consumers validate structure independently of the framing choice.
Things to check
- The Python documentation explicitly states that JSON is not a framed protocol and repeated dump() calls produce an invalid file; this is a direct quote from the json module reference.
- raw_decode() is documented as returning a two-tuple of the decoded object and the index where the document ended, designed for strings with extraneous data at the end.
- The example code runs on Python 3.8+ with only the standard library; no third-party packages are required.
- json.loads() on concatenated objects raises JSONDecodeError with message containing 'Extra data', not a silent truncation.
- A JSON array containing multiple objects is a single valid JSON document; each element is an object, not a separate document.
- JSON Schema required properties check for presence of the key; a null value satisfies required but may fail a type constraint.
Where this applies
The Python documentation confirms the framing issue and the dump/load API but does not prescribe a specific multi-object serialization strategy; the JSON Lines approach is inferred from raw_decode's documented ability to parse a JSON document from a string with extraneous data at the end. JSON Schema source covers object property validation but does not address stream framing. This guide does not cover binary framing, length-prefixed protocols, or custom serialization formats beyond the Python json module.