object_pairs_hook Catches Duplicate JSON Keys
object_pairs_hook receives every JSON object as a list of pairs, so duplicate keys can be rejected or collected instead of silently overwriting.
Code
import json
raw = '{"role": "viewer", "level": 3, "role": "admin"}'
# default parsing: the later key silently overwrites the earlier one, so duplicates go unnoticed
print("default:", json.loads(raw))
def reject_duplicates(pairs):
seen = {}
for key, value in pairs:
if key in seen:
raise ValueError(f"duplicate key: {key}")
seen[key] = value
return seen
try:
json.loads(raw, object_pairs_hook=reject_duplicates)
except ValueError as exc:
print("rejected:", exc)
def collect(pairs):
out = {}
for key, value in pairs:
out.setdefault(key, []).append(value)
return out
# alternatively keep every duplicate: each occurrence lands in the list
print("collected:", json.loads(raw, object_pairs_hook=collect))How it works
object_pairs_hook Catches Duplicate JSON Keys is built around the functions reject_duplicates and collect.
Repetition is confined to for key, value in pairs — the rest of the file is straight-line. When the guard condition holds, ValueError is thrown rather than a bogus value returned.
Caveats
- The guard
key in seenshort-circuits the flow with an earlyraisewhen its condition holds.
Using it
Entry signature: def reject_duplicates(pairs)
The demo output is labeled (default:, rejected:, collected:), so every printed line maps back to its originating operation.
reject_duplicates is what another module would consume; nothing else here is load-bearing for callers.
Key statements
raise ValueError(f"duplicate key: {key}")
seen[key] = value
return seen
try:
json.loads(raw, object_pairs_hook=reject_duplicates)
except ValueError as exc:
print("rejected:", exc)
def collect(pairs):
out = {}
def reject_duplicates(pairs):
seen = {}
for key, value in pairs:
if key in seen:
raise ValueError(f"duplicate key: {key}")
seen[key] = value
return seen
def collect(pairs):
out = {}
for key, value in pairs:
out.setdefault(key, []).append(value)
return out
Interactive Tools for This Topic
FAQ
- How does the snippet fail?
- Validation comes first — `ValueError` marks the failure at `key in seen`, before any partial work happens.
- Any setup needed beyond the language runtime?
- None — the language runtime is the only requirement. Every import resolves inside the standard library — `json`. The file defines `reject_duplicates`, `collect` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.