Reject Duplicate Keys and NaN in Python JSON: Parsing Hooks and Float Overflow Checks
Reproduce json.loads defaults and validate a UTF-8 object boundary that rejects duplicate keys, nonfinite literals, and float overflow with 11 rejection cases.
When accepting HTTP request bodies or configuration JSON in Python, successful json.loads() parsing does not establish your input contract. Reject duplicate keys and NaN through parsing hooks, and separately check values such as 1e400 that become infinity during conversion. This article implements a small boundary that accepts UTF-8 objects and uses actual execution results to show its acceptance and rejection rules.
Two identical keys and a cracked crystal stop at an inspection tray while a teal token passes through. A conceptual illustration of JSON input validation rejecting duplicate keys and nonfinite values.
Written and documentation checked: 2026-11-27. Tested environment: Linux x86_64, CPython 3.12.14, standard library only. The linked Python 3.12 documentation displayed version 3.12.16 when checked.
You cannot detect duplicates after discarding values
If you turn {"role":"reader","role":"admin"} into an ordinary dictionary before checking it, the earlier value may already be gone. In the execution below, only the final value, admin, remains. An API carrying permissions or execution options should explicitly decide its policy at the input boundary. Do not assume different parsers will select the same value.
RFC 8259 §4 recommends unique object names with SHOULD. Here, the service contract is narrower and rejects duplicates. Requiring a top-level object is likewise this example's policy, rather than a rule for all JSON syntax.
Separate three checks
| Check | Role in the example | Consequence of omitting it |
| Key pairs | Reject duplicates within one object | Earlier values disappear after dictionary construction |
| Special constants | Reject NaN, Infinity, and -Infinity | Unexpected numeric values enter calculations |
| Float conversion | Require a finite float result | 1e400 becomes infinity |
The APIs used are object_pairs_hook, parse_constant, and parse_float in Python's json documentation. Setting strict=True alone does not establish these three policies; that option concerns control characters in strings.
An executable input function
Save this as json_input_demo.py. It does not start an HTTP server: it passes byte strings representing received raw bodies directly to the function.
unique_object() builds a fresh dictionary for each object. It accepts x in separate objects but rejects duplicates inside a nested object. The keys a and \u0061 collide after decoding. Unlike searching the raw text for keys with a regular expression, this approach does not need a separate interpretation of escape sequences.
Using only parse_constant would miss 1e400. That token is not a special literal like NaN, so the float conversion function checks math.isfinite(). This policy permits finite binary floating-point values; it does not guarantee exact decimal preservation. Inputs requiring exact decimal calculations, such as monetary amounts, need a separate type and range contract.
Actual verification results
The output below was produced in the environment stated above. Every assertion passed.
The checks cover three default behaviors, two accepted inputs, and eleven rejected inputs. Invalid UTF-8 and a second trailing JSON value are rejected too. The test groups rejection exceptions under the ValueError family; it does not implement or verify production HTTP statuses or error responses.
Service contracts still needed after parsing
This function does not check required fields, allowed fields, permissions, or numeric ranges. For example, {"rate":-100} passes its parsing policy. Run separate schema validation before business processing. Fields with potentially surprising Python type relationships, such as bool and int, also need explicit service rules.
The 4096-byte limit checks the body already supplied to the function. It does not bound memory while receiving HTTP data. A real server also needs size and time limits in its body collection layer. Deep nesting causing RecursionError, escaped lone surrogates, complete Unicode validity, load, and performance are outside this example's verification scope. Do not treat the function as a complete security sandbox or a validator for every RFC condition.
Rejecting nonfinite numbers on output requires a separate serialization policy, such as json.dumps(value, allow_nan=False). Reject duplicates before discarding them, and distinguish numeric conversion from business validation so that each error has a clear handling boundary.