Detecting Duplicate JSON Keys in LLM Output with Python's object_pairs_hook
Python's json.loads silently keeps only the last value when a JSON object contains duplicate keys, discarding earlier ones without warning. The object_pairs_hook parameter intercepts the full ordered list of key-value pairs before dict construction, enabling explicit duplicate detection at parse time.
On this page
Key idea
Use json.loads with object_pairs_hook to receive every key-value pair in order before the dictionary is built, then check for repeated keys and raise an error or log a warning. The default decoder follows a last-wins policy chosen by CPython, since RFC 7159 does not specify how duplicates should be handled. This makes silent data loss the default failure mode when an LLM emits malformed JSON with repeated field names.
LLM JSON output can contain duplicate keys that json.loads silently collapses
When a large language model produces JSON, it sometimes emits the same key more than once inside a single object. This can happen when the model is instructed to fill in a template that already contains a default value, or when it attempts to revise an answer within the same response. The Python standard library json module handles this by keeping only the last value for each key and discarding all earlier occurrences without raising any exception or emitting a warning.
The Python documentation states this behavior explicitly: the RFC specifies that names within a JSON object should be unique, but does not mandate how repeated names should be handled. By default, the module ignores all but the last name-value pair for a given name. For example, parsing the string '{"x": 1, "x": 2, "x": 3}' returns {'x': 3} with no indication that two values were lost. In an LLM pipeline where the model might output a field like "status" twice with conflicting values, the consumer silently receives only the final one.
The recommendation is to pass an object_pairs_hook callable to json.loads. This hook receives the complete ordered list of key-value pairs for every JSON object literal in the document before the dictionary is constructed, giving you the opportunity to inspect the raw sequence and detect duplicates at parse time rather than discovering missing data downstream.
import json
raw = '{"x": 1, "x": 2, "x": 3}'
result = json.loads(raw)
print(result) # {'x': 3} (values 1 and 2 silently discarded)Why the default behavior exists and what object_pairs_hook trades away
RFC 7159, which obsoleted RFC 4627, states that names within a JSON object should be unique but does not prescribe how a parser must react when it encounters repeated names. By default, the module does not raise an exception; instead, it ignores all but the last name-value pair for a given name. The JSON Schema specification similarly treats objects as mappings from string keys to values, implying uniqueness as a structural expectation rather than a parse-time enforcement requirement.
The object_pairs_hook parameter, added in Python 3.1, changes the decoding contract. object_hook receives the finished dict after construction and returns a replacement object. object_pairs_hook receives the ordered list of pairs before any dict is built and must return the final object itself. If both are set, object_pairs_hook takes precedence. This means you take over dictionary construction entirely. You lose the convenience of the default fast path and must handle the pair list yourself.
The trade-off is between silent data loss and explicit control. If you do not need duplicate detection, the default decoder is faster because it avoids the Python-level callback for every object literal. If you do need it, the hook adds a small per-object overhead but converts an invisible data corruption into a visible, actionable failure at the exact parse site.
# object_pairs_hook receives the full ordered list before any dict is built
# pairs = [("x", 1), ("x", 2), ("x", 3)]
# You must return the final object yourselfA minimal hook that raises on duplicate keys
The following example demonstrates both the default silent overwrite and a one-line object_pairs_hook that collects keys into a dictionary and raises ValueError when it encounters a duplicate. The hook runs for every JSON object literal in the document, so nested objects are also checked. The output shows the exact key that caused the collision, making it straightforward to identify which field the LLM emitted twice.
Prerequisites: Python 3.1 or later for object_pairs_hook availability. On Python 3.6 and above, all optional parameters are keyword-only, so you must pass object_pairs_hook=... as a keyword argument.
import json
# Default behavior: last value wins, no warning
raw = '{"x": 1, "x": 2, "x": 3}'
print(json.loads(raw)) # {'x': 3}
# Detect duplicates with object_pairs_hook
def reject_duplicates(pairs):
seen = {}
for key, value in pairs:
if key in seen:
raise ValueError(f"Duplicate key: {key!r}")
seen[key] = value
return seen
try:
json.loads(raw, object_pairs_hook=reject_duplicates)
except ValueError as e:
print(e) # Duplicate key: 'x'
# Nested objects are also checked
raw_nested = '{"a": {"x": 1, "x": 2}}'
try:
json.loads(raw_nested, object_pairs_hook=reject_duplicates)
except ValueError as e:
print(e) # Duplicate key: 'x'When duplicate-key detection helps and when it does not
This technique is useful in three concrete scenarios. First, validating LLM structured output where the model may hallucinate repeated fields in a template. Second, parsing hand-edited JSON configuration files where a developer accidentally pastes a block twice. Third, merging JSON documents from multiple sources where key collisions indicate a logic error in the merge step. In all three cases, the goal is to convert a silent data loss into a loud failure at the boundary where the JSON enters your system.
It does not fix the prompt that produced the duplicate, does not repair the output, and does not replace JSON Schema structural validation. JSON Schema checks required fields, types, and additionalProperties constraints, but it operates on the already-parsed object, by which point duplicates are gone. The object_pairs_hook catches the problem one layer earlier, at the text-to-structure boundary. It also only works when you control the parsing call site; if a third-party library has already called json.loads without a hook, you cannot retroactively detect duplicates.
The per-object overhead is small for typical documents but measurable for very large JSON payloads with thousands of object literals, since the hook is a Python-level function call for each object literal. In practice this is usually negligible relative to model inference time, but you should measure on your workload if parsing very large documents.
# This hook does NOT replace JSON Schema validation.
# Schema checks: required fields, types, enum constraints, additionalProperties
# object_pairs_hook checks: key uniqueness at parse time
# They operate at different layers and solve different problems.Applicability
- Is the JSON being produced by an LLM or another source that might emit duplicate keys, or is it generated by a serializer that guarantees uniqueness?
- Are you using Python 3.6 or later, where object_pairs_hook must be passed as a keyword argument?
- Does the consuming code rely on the default last-wins behavior, meaning a strict duplicate check would break existing valid inputs?
- Is the JSON parsed at a call site you control, rather than inside a third-party library that already called json.loads without a hook?
- Do you also need JSON Schema validation for required fields and types, which object_pairs_hook does not provide?
Where this applies
The object_pairs_hook approach detects duplicate keys at parse time but does not correct the LLM prompt, repair the output, or replace structural validation via JSON Schema. It adds a small Python-level callback overhead for every JSON object literal in the document. It only works when you control the json.loads call site and cannot retroactively inspect data that has already been parsed by another library. The hook must return the final object itself, so you take over dictionary construction and lose the default fast path.