Reject Duplicate JSON Keys and Non-Finite Numbers in Python
A game configuration contains two retries fields. A reviewer reads the first value, while the application uses the second. Another configuration loads successfully but gives a timeout the value Infinity.
For a small configuration file, reject these inputs while parsing, before applying defaults or changing application state. This Python 3 example uses only the standard library and keeps the validation policy in one reusable module.
Reproduce the Permissive Defaults
The default decoder accepts repeated object names and keeps the last value. It also accepts special numeric tokens:
Python documents these behaviors in its JSON decoder reference . Once the result is a dictionary, the overwritten value is gone. A later schema check cannot recover the original pair of entries.
The exponent example is a separate problem: 1e400 has valid JSON number syntax, but conversion to a Python float overflows to infinity. Rejecting only the literal token Infinity leaves that route open.
Define the Configuration Contract
Use an explicit policy for this loader:
| Input property | Rule |
|---|---|
| Input type | An already decoded Python string |
| Root value | One JSON object |
| Object names | Unique within each individual object |
| Nested values | Apply the same checks inside objects and arrays |
| Special numeric tokens | Reject NaN, Infinity, and -Infinity |
| Fractional or exponent numbers | Accept only when conversion produces a finite float |
| Integers | Keep the decoder’s default integer conversion |
Names remain case-sensitive. mode and Mode are different names. Two separate objects may each contain mode; uniqueness is local to one object. Escape sequences are decoded before comparison, so "mode" and "\u006dode" collide.
This is a configuration policy, not a complete application schema. It does not check required fields, allowed names, numeric ranges, or string contents. An empty object is valid at this stage. Likewise, finite float conversion does not promise exact decimal arithmetic: tiny values may underflow to zero, and ordinary fractions may round.
Reject Ambiguity During Decoding
Save this module as config_json.py:
| |
The decoder’s
object_pairs_hook, parse_constant, and parse_float options
intercept object pairs, special constants, and decimal/exponent tokens respectively. The pair hook runs for every object, including objects inside arrays. Its membership check catches a repeated key even when its first value is null or false.
math.isfinite
checks the converted float. Keeping that check inside parse_float avoids a separate recursive walk through the completed configuration.
Setting strict=True alone does not implement these rules; that decoder option controls unescaped control characters in strings. allow_nan=False belongs to JSON encoding and is not a decoding switch.
Load Before Applying Settings
After saving the module, run this example beside it:
For a file, open it with an explicit encoding, such as open(path, encoding="utf-8"), and pass the text to this helper. This contract expects UTF-8 without a BOM; agree on encoding with the producer rather than guessing it.
Next, validate the application’s schema and only then apply the settings. A finite timeout of -5 still needs rejection by that schema. If a setting must be a JSON integer, use an exact type check such as type(value) is int, because Python booleans also satisfy isinstance(value, int).
Catch ValueError at the configuration boundary to report rejected content. JSON syntax errors use JSONDecodeError, a subclass of ValueError; hook errors use ordinary ValueError and do not include a full object path. File access and decoding failures also need handling there. Bound file size before reading and parsing external input; these hooks do not impose memory or nesting limits.
Test Nested Duplicates and Numeric Boundaries
Save this as test_config_json.py beside the module, then run python3 test_config_json.py with your Python 3 interpreter:
| |
Keep duplicate-key cases as literal JSON fixtures. Building them with a Python dictionary and then serializing it would erase the duplicate before the loader ever receives the input. Add real configuration examples and application schema tests alongside these parser boundary checks.