Python JSON: Reject Duplicate Keys, NaN and Infinity
Stop silent JSON data loss in Python. Reject duplicate keys and NaN, catch float overflow, separate parser and policy errors, and run a 451-check lab.
Successful json.loads() does not establish that a document meets your ingestion policy. Python can retain only the last occurrence of a repeated object name and accept NaN or Infinity by default. Use object_pairs_hook before pairs become a dictionary, reject non-standard constants with parse_constant, and choose a numeric conversion policy separately. The checked loader below also rejects float overflow, but it is not a complete schema, Unicode or resource-isolation validator.
A valid-looking dictionary can hide an ambiguous document
An ingestion endpoint receives two values for the same field, yet its validation log shows only one. The application then checks a perfectly ordinary dictionary and reports success. The missing evidence may have disappeared during decoding, before business validation even started. This is a parsing-policy problem, not necessarily a missing schema rule.
Use an invented example such as {"region":"east","region":"west"}. The default Python decoder returns one region entry containing west. Re-serializing that dictionary produces a clean-looking document, but it cannot show that the earlier region value existed. A later audit of only the decoded dictionary will miss the ambiguity.
This guide builds a small loader for decoded Python strings and demonstrates its behavior with the standard library. The exact published fixture passed 451 checks on Python 3.12.14. It covers nested duplicates, escaped member names, numeric constants, overflow, byte boundaries and serialization. These are local correctness fixtures, not a claim of exhaustive parser fuzzing or a benchmark.
strict=True does not define your entire JSON policy
The json decoder uses strict=True by default, but that option concerns unescaped control characters inside strings. It is not a switch that rejects every interoperability problem. The fixture confirms that strict=True still accepts a duplicate name using the last value and still accepts the non-standard NaN token.
RFC 8259 says object member names should be unique. It describes divergent receiver behavior when they are not; duplicate rejection is therefore an explicit policy you should choose and document. The JSON number grammar, separately, does not include NaN or Infinity. Keep that distinction clear when explaining a rejection to a producer.
A parser may accept more than a particular application wants to accept. Conversely, a JSON scalar such as null, true, a string or a number can be a valid top-level JSON value even if an API requires an object. Parse first under an intentional policy, then enforce that API-specific shape. Do not label every application rejection a syntax error.
| Concern | Relevant mechanism | Important boundary |
|---|---|---|
| Repeated object names | object_pairs_hook | Inspect decoded pairs before constructing dict |
| NaN / Infinity / -Infinity tokens | parse_constant | Does not intercept every ordinary numeric literal |
| Exponent converted beyond float range | parse_float plus finite check | Finiteness does not guarantee exactness |
| Raw control characters in a string | Default strict=True | Not a duplicate or number-policy switch |
| Required fields and allowed properties | Application/schema validation after decoding | Cannot restore pairs discarded by an earlier decoder |
Source: Python 3.12 json: decoding hooks, strict strings and interoperability ↗
Reject repeated decoded names at every object level
The object_pairs_hook receives the pairs for each JSON object. Construct a dictionary only after checking whether a name already exists. Raise a policy exception on repetition, including when both values are identical. Equal values do not remove the ambiguity or establish that repeated members are acceptable to downstream consumers.
The hook runs for nested objects too. A repeated name inside an object in an array is still a duplicate within that object. The same name in two separate objects is fine under this policy, as are repeated array elements. Counting every name across the entire document would reject ordinary data that contains repeated field names in independent records.
Names are compared after JSON string escapes are decoded. The fixture therefore rejects a literal a and an escaped \u0061 in the same object. It deliberately does not lowercase or Unicode-normalize names: a and A stay different, as do composed and decomposed accented names. If an application later normalizes identifiers, audit that additional collision policy separately.
Source: Python 3.12 json: decoding hooks, strict strings and interoperability ↗
Reject constants and float overflow with different hooks
The parse_constant hook handles the special NaN, Infinity and -Infinity spellings accepted by Python. A callback that raises JSONPolicyError can reject them. It does not mean that ordinary numeric syntax has been checked for the range and precision your application needs. In particular, 1e400 uses ordinary exponent syntax.
In this tested runtime, default conversion of 1e400 produces an infinite float. The loader below supplies parse_float and checks math.isfinite after conversion. This rejects the overflow while retaining the usual float representation for accepted fractional or exponent values. It is a range policy for this application, rather than a statement that 1e400 is invalid JSON grammar.
Finiteness is a narrower guarantee than numeric fidelity. The lab confirms that 1e-400 can underflow to zero and that the binary float produced from 0.1 is not the exact decimal fraction. Integer tokens continue to use Python integers; the fixture retains 9007199254740993 exactly. Do not assume another consumer preserves that same integer or decimal precision.
Source: RFC 8259: JSON objects, number grammar and interoperability ↗
Run the complete checked-loader lab
Save this code as json_policy_lab.py and run it with Python 3.12. It uses only the standard library and has no network, database or file writes. The loader accepts strings containing at most 4096 UTF-8 bytes. The test helper raises explicit assertions, so running Python with optimization does not silently disable the comparisons.
The fixed cases establish default behavior and specific policy boundaries. Another 201 constructed integer cases compare the loader with independently assembled expected dictionaries; 201 duplicate variants must raise the policy exception. The full run totals 451 checks. A successful run prints the count, while an unexpected result stops execution.
Observe the exception split. Broken JSON syntax normally raises JSONDecodeError. Our hooks raise JSONPolicyError, which is a separate ValueError subclass. In the NaN-followed-by-trailing-text case, the constant hook rejects before the decoder examines all later syntax. An ingestion service should not depend on one particular error being the first problem found in a document.
import json
import math
from decimal import Decimal
MAX_BYTES = 4096
class JSONPolicyError(ValueError):
pass
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise JSONPolicyError('Duplicate object member name')
result[key] = value
return result
def reject_constant(_token):
raise JSONPolicyError('Non-standard numeric constant')
def finite_float(token):
value = float(token)
if not math.isfinite(value):
raise JSONPolicyError('Number exceeds finite float range')
return value
def load_checked(text):
if not isinstance(text, str):
raise TypeError('Pass a decoded Python string')
if len(text.encode('utf-8')) > MAX_BYTES:
raise JSONPolicyError('JSON text exceeds the byte budget')
return json.loads(text, object_pairs_hook=unique_object,
parse_constant=reject_constant,
parse_float=finite_float)
checks = 0
def check(condition):
global checks
if not condition:
raise AssertionError('Unexpected result')
checks += 1
def rejects(call, error):
global checks
try:
call()
except error:
checks += 1
else:
raise AssertionError('Expected rejection')
# Actual default behavior, not a recommended policy.
check(json.loads('{"x":1,"x":2}', strict=True) == {'x': 2})
check(math.isnan(json.loads('NaN', strict=True)))
check(math.isinf(json.loads('1e400')))
check(json.loads('{"a":{"x":1,"x":2}}') == {'a': {'x': 2}})
# Reject duplicates at any object level, including escaped names.
for text in ['{"x":1,"x":2}', '{"x":1,"x":1}',
'{"outer":{"x":1,"x":2}}', '[{"x":1,"x":2}]',
r'{"a":1,"\u0061":2}']:
rejects(lambda text=text: load_checked(text), JSONPolicyError)
for token in ['NaN', 'Infinity', '-Infinity', '1e400', '-1e400']:
rejects(lambda token=token: load_checked('{"n":'+token+'}'), JSONPolicyError)
# Syntax errors remain JSONDecodeError, separate from policy errors.
for text in ['{"x":1,}', '{x:1}', '[01]', '[+1]', '[.5]',
'/*comment*/{}', '{}{}', 'NaN trailing', '"line\nbreak"']:
# NaN is rejected by our hook before the trailing syntax is examined.
error = JSONPolicyError if text == 'NaN trailing' else json.JSONDecodeError
rejects(lambda text=text: load_checked(text), error)
check(json.loads('"line\nbreak"', strict=False) == 'line\nbreak')
check(load_checked(r'"line\nbreak"') == 'line\nbreak')
check(load_checked('[{"x":1},{"x":2}]') == [{'x':1},{'x':2}])
check(load_checked('{"a":1,"A":2}') == {'a':1,'A':2})
check(len(load_checked('{"é":1,"é":2}')) == 2)
check(load_checked('[1,1,null,true,false]') == [1,1,None,True,False])
for text, expected in [('null',None),('true',True),('"ok"','ok'),('42',42)]:
check(load_checked(text) == expected)
check(load_checked('9007199254740993') == 9007199254740993)
check(load_checked('1e-400') == 0.0) # Finiteness does not prevent underflow.
check(Decimal.from_float(load_checked('0.1')) != Decimal('0.1'))
check(json.loads('1e400', parse_float=Decimal).is_finite())
check(json.loads('1.10', parse_float=Decimal) == Decimal('1.10'))
rejects(lambda: json.dumps(Decimal('1.10')), TypeError)
# Byte limits: not character counts, and not a depth/time guarantee.
check(len(load_checked('"'+'a'*4094+'"')) == 4094)
check(len(load_checked('"'+'é'*2047+'"')) == 2047)
rejects(lambda: load_checked('"'+'a'*4095+'"'), JSONPolicyError)
rejects(lambda: load_checked('"'+'é'*2048+'"'), JSONPolicyError)
rejects(lambda: load_checked(b'{}'), TypeError)
for value in [float('nan'),float('inf'),float('-inf')]:
rejects(lambda value=value: json.dumps({'n':value}, allow_nan=False), ValueError)
check(json.dumps({'n':1.5}, allow_nan=False) == '{"n": 1.5}')
collision = json.dumps({1:'first','1':'second'}, allow_nan=False)
rejects(lambda: load_checked(collision), JSONPolicyError)
# Constructed valid cases: independent expected dictionaries and integers.
for n in range(-100,101):
text = '{"n":'+str(n)+',"nested":{"n":'+str(n+1)+'}}'
check(load_checked(text) == {'n':n,'nested':{'n':n+1}})
duplicate = '{"n":'+str(n)+',"n":'+str(n+1)+'}'
rejects(lambda duplicate=duplicate: load_checked(duplicate), JSONPolicyError)
print(f'PASS: {checks} checks; standard-library parsing only')
Choose Decimal intentionally when exact decimal values matter
For an application that needs decimal values rather than binary floats, parse_float=Decimal is another conversion choice. The lab confirms that Decimal can represent the tested 1e400 value as finite and preserves the tested decimal value 1.10. That choice changes the decoded Python types and the range policy; it is not equivalent to the finite-float loader.
Use the same duplicate and constant hooks if those policies remain required. Then define allowed decimal precision, exponent, rounding and output representation for the receiving system. A finite Decimal can still be outside an application’s accepted range. Choose those constraints from the data contract rather than from the fact that a parser returned successfully.
Decimal also needs an intentional serialization strategy. The standard encoder does not serialize a Decimal by default, as the fixture verifies. Converting it with default=str would make a JSON string, changing the contract. Decide whether the API expects a number or a string and test both sides; do not add a generic conversion solely to suppress a TypeError.
Validate the output path as well as the input path
For Python float output, json.dumps(..., allow_nan=False) rejects non-finite float values. The fixture checks NaN and both infinities, as well as an ordinary finite output. This encoder option is separate from decoder hooks. A service can read under one policy and later create a non-finite value during calculation, so test the outbound boundary too.
Output member names need attention as well. A Python dictionary can contain both the integer key 1 and the string key "1". Encoding can turn these into the same JSON member name; allow_nan=False does not solve that collision. The lab generates that document and confirms that the checked decoder rejects it.
If your output contract requires string keys, enforce that requirement before encoding. Review any code that renames, normalizes or merges keys after validation. Avoid a decode-encode cleanup pass as a substitute for rejecting ambiguous input: by then the earlier member values may already be gone. Keep failure handling attached to the stage where information is still available.
Source: Python 3.12 json: decoding hooks, strict strings and interoperability ↗
Integrate the policy without overstating its protection
The 4096-byte guard is a teaching budget, not a universal production recommendation. It measures UTF-8 bytes rather than Python character count; the lab checks both ASCII and multibyte boundaries. Because the function receives an existing string, it cannot stop a web server from reading an oversized body before the function is called. Bound request acquisition and decoding at the appropriate transport layer.
A byte budget also does not impose a maximum nesting depth, CPU deadline, schema, Unicode-scalar policy or complete interoperability profile. Small deeply nested inputs can still be problematic for a recursive parser. Add appropriate boundary controls for the real workload and report their scope honestly. Do not advertise this loader as a complete hostile-input sandbox.
At the API boundary, catch syntax and policy failures deliberately, map them to the application’s documented response, and avoid logging a full customer payload or sensitive member names. The example uses generic policy messages. JSONDecodeError exposes line and column information that can help a producer locate a syntax problem; retain only the diagnostic detail the service needs.
After decoding, validate required properties, types and business ranges. That is where the existing JSON Schema guide becomes useful. Keep a regression fixture for the original failure, including raw input that represents the ambiguity, within your retention rules. The resulting pipeline should preserve enough evidence to explain a rejection and accept only the data meaning your consumers actually share.
Your next steps
- Reject duplicate names while decoding object pairs. Once a dictionary has replaced earlier occurrences, ordinary schema validation cannot recover the original ambiguity.
- Treat non-standard constants, numeric range, numeric precision and output serialization as separate decisions. parse_constant alone does not catch a finite-looking exponent that overflows float.
- Keep the original request within your data-handling policy, report bounded error details, and validate the decoded application shape after parser checks. Test the same loader and runtime used by production.
Sources & official resources
Linked resources checked on 2026-10-31. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →