A JSON object with the same name twice can silently keep one value unless the parser enforces a policy.
Python JSON duplicate names: reject ambiguous object fields
Operation contract
A signed instruction should not let two parsers disagree about the tenant field. object_pairs_hook receives ordered pairs for each object; the hook rejects a repeated name before producing a dict. This is parser-level validation. It does not authenticate the payload, enforce its complete schema, or reject a different spelling of the same logical identifier after case normalization.
Failure and ownership boundary
The default decoder accepts duplicate names and keeps a later value. Applying a strict hook to every object is simple but costs a set per object. Set a byte limit before parsing untrusted input. Keep the original bytes for signature verification when the protocol signs bytes; reserializing a parsed dict is not equivalent to those original bytes.
Working program
import json
def unique_names(pairs):
result = {}
for name, value in pairs:
if name in result:
raise ValueError("duplicate name: " + name)
result[name] = value
return result
payload = '{"tenant":"north-47","tenant":"south-47"}'
try:
json.loads(payload, object_pairs_hook=unique_names)
except ValueError as error:
print(str(error))Output
duplicate name: tenantCosts and limits
The hook visits each key once and retains the decoded object. A duplicate check is O(keys) expected time per object with O(keys) extra membership state.
Common Mistakes
- Do not rely on a default decoder to reject duplicate names.
- A parsed object is not the byte sequence that a signature covered.
- Case folding or Unicode normalization may need a separate field-name rule.
