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:

1
2
3
4
5
6
7
import json
import math

config = json.loads('{"retries": 2, "retries": 8, "timeout": NaN}')
print(config["retries"])               # 8
print(math.isnan(config["timeout"]))  # True
print(json.loads('{"timeout": 1e400}')["timeout"])  # inf

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 propertyRule
Input typeAn already decoded Python string
Root valueOne JSON object
Object namesUnique within each individual object
Nested valuesApply the same checks inside objects and arrays
Special numeric tokensReject NaN, Infinity, and -Infinity
Fractional or exponent numbersAccept only when conversion produces a finite float
IntegersKeep 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
import json
import math


def unique_object(pairs):
    result = {}
    for key, value in pairs:
        if key in result:
            raise ValueError(f"Duplicate JSON key: {key!r}")
        result[key] = value
    return result


def reject_constant(token):
    raise ValueError(f"Unsupported JSON numeric token: {token}")


def finite_float(token):
    value = float(token)
    if not math.isfinite(value):
        raise ValueError(f"JSON number exceeds finite float range: {token}")
    return value


def loads_config(text):
    if not isinstance(text, str):
        raise TypeError("Expected decoded JSON text")
    value = json.loads(
        text,
        object_pairs_hook=unique_object,
        parse_constant=reject_constant,
        parse_float=finite_float,
    )
    if not isinstance(value, dict):
        raise ValueError("Configuration root must be a JSON object")
    return value

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:

1
2
3
4
5
6
from config_json import loads_config

text = '{"retries": 2, "timeout": 1.5, "servers": [{"name": "primary"}]}'
config = loads_config(text)
print(config["retries"], config["timeout"], config["servers"][0]["name"])
# 2 1.5 primary

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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from config_json import loads_config


def must_reject(text):
    try:
        loads_config(text)
    except ValueError:
        return
    raise AssertionError(f"Expected rejection: {text}")


assert loads_config("{}") == {}
assert loads_config('{"items": [{"id": 1}, {"id": 2}]}') == {
    "items": [{"id": 1}, {"id": 2}]
}
assert loads_config('{"a": null, "b": false, "c": "NaN"}') == {
    "a": None, "b": False, "c": "NaN"
}
assert loads_config('{"Mode": 1, "mode": 2}') == {"Mode": 1, "mode": 2}
assert loads_config('{"x": 1e308, "y": -2.5, "z": 0}') == {
    "x": 1e308, "y": -2.5, "z": 0
}

for text in (
    '{"x": 1, "x": 2}',
    '{"x": null, "x": false}',
    '{"outer": {"x": 1, "x": 2}}',
    '{"items": [{"x": 1, "x": 2}]}',
    r'{"mode": 1, "\u006dode": 2}',
    '{"x": NaN}',
    '{"x": Infinity}',
    '{"x": -Infinity}',
    '{"items": [0, NaN]}',
    '{"x": 1e400}',
    '{"outer": {"x": -1e400}}',
    '[]', 'null', '42', '"text"',
    '{"x": 1,}', '{} {}',
):
    must_reject(text)

try:
    loads_config(b"{}")
except TypeError:
    pass
else:
    raise AssertionError("Bytes must be decoded explicitly")

print("Configuration JSON checks passed")

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.