Hardening Python JSON Parsing: Size Limits and parse_int, parse_float, parse_constant
A reliable JSON parsing strategy that caps input size and uses parse_int, parse_float, and parse_constant to control number decoding and reject non-standard constants before they become resource drains.
On this page
Key idea
The standard json module does not limit input size or nesting depth, so untrusted data can exhaust CPU and memory during decoding. A robust approach is to enforce an explicit byte-length limit before calling json.loads or json.load, and to pass custom callables for parse_int, parse_float, and parse_constant. parse_int lets you redirect integer literals to a safer type or reject overly long digit sequences. parse_float lets you choose Decimal or a validating function instead of the default binary float. parse_constant is invoked only for the non-standard tokens NaN, Infinity, and -Infinity, allowing you to raise an error or substitute a safe value. Combine these with a top-level exception handler that catches both JSONDecodeError and any custom exceptions from the parse hooks, and always reject the document if the byte count exceeds your chosen threshold.
Enforcing a strict input size cap
Python's json module explicitly warns that a malicious JSON string may consume considerable CPU and memory. The documentation also states that the module does not impose any limits on the size of accepted texts, nesting depth, or string length. Thus, a pre-parse byte limit is your first line of defense, and it must be enforced by the caller, not by the decoder.
For a bytes or str document, check the length before invoking json.loads. For file-like objects, read at most MAX_SIZE + 1 bytes and reject if you received more. This prevents the decoder from ever seeing a document that exceeds your budget, avoiding both CPU-heavy parsing and memory allocation for an oversized object tree.
MAX_SIZE = 1_000_000
def check_size(s: str) -> None:
if len(s) > MAX_SIZE:
raise ValueError(f'JSON exceeds size limit of {MAX_SIZE} characters')
Controlling integer literals with parse_int
parse_int is called for every integer token, receiving the numeric substring as a str. By default, int() is used, and since Python 3.11 the interpreter caps integer string length to mitigate denial of service. For older versions, a huge digit sequence like 10**1000000 creates a very large int object, which wastes memory and slows later operations.
Use parse_int to impose your own digit-length limit or to convert to Decimal, float, or a custom validated type. For example, you might map any integer literal longer than 100 digits to 0 or raise an error. This hook gives you fine-grained control over the exact integers that enter your application, complementing the size cap.
import json
from decimal import Decimal
def parse_int_safe(s: str) -> int:
if len(s) > 100:
raise ValueError(f'Integer too long: {len(s)} digits')
return int(s)
result = json.loads('{"big": 12345678901234567890}', parse_int=parse_int_safe)
print(result['big'])
Managing reals and non-standard constants with parse_float and parse_constant
parse_float controls how JSON real numbers are decoded. The default float() produces binary floating-point values that can silently lose precision for decimal values with many digits. Passing Decimal as parse_float gives you arbitrary-precision decimals, at the cost of performance. Alternatively, you can validate the numeric string and return a float only when the range is acceptable.
parse_constant is special: it is only called for the literal strings '-Infinity', 'Infinity', and 'NaN', which are outside the JSON specification (RFC 7159) but accepted by default. This hook lets you reject them outright or replace them with a safe value. Note that this hook is not called for null, true, or false (as of Python 3.1). A typical implementation raises ValueError, which the caller can catch alongside JSONDecodeError.
import json
from decimal import Decimal
def reject_const(token: str):
raise ValueError(f'Non-standard constant: {token}')
json.loads('{"x": 1.5, "y": -2.25}', parse_float=Decimal) # Decimal('-2.25')
try:
json.loads('{"z": NaN}', parse_constant=reject_const)
except ValueError as e:
print('Caught', e)
Combining all measures in a hardened loader
A robust loader puts size capping and all three parse hooks into one function, then wraps everything in a clear exception policy. The function should reject oversized input before any parsing begins, and it should catch both JSONDecodeError for malformed syntax and ValueError for hook-level rejections. The example below defines safe_loads that raises a specific error for each failure mode, so a caller can distinguish a too-large document from a bad number token.
This design does not replace schema validation. After successful parsing, you still need to validate the object structure (required keys, types, allowed values) using a tool like JSON Schema. The parse hooks protect the decoding stage; schema validation protects the application stage. Limiting input size and controlling number tokens together reduce the attack surface without eliminating the need for explicit business-rule checks.
import json
from decimal import Decimal
MAX_SIZE = 1_000_000
def safe_loads(text: str):
if len(text) > MAX_SIZE:
raise ValueError('JSON exceeds size limit')
return json.loads(
text,
parse_int=lambda s: int(s) if len(s) < 100 else 0,
parse_float=Decimal,
parse_constant=lambda s: (_ for _ in ()).throw(
ValueError(f'Non-standard constant: {s}')
)
)
try:
data = safe_loads('{"a": 12345678901234567890, "b": 1.5, "c": NaN}')
except (ValueError, json.JSONDecodeError) as e:
print('Error:', e)
Applicability
- Is the input from an untrusted source (user input, external API, file upload)?
- Do you need to preserve decimal precision beyond Python's binary float?
- Do you need to reject NaN, Infinity, and -Infinity because they violate the JSON spec?
- Can your application tolerate a hard byte cap that truncates legitimate large documents?
- Are you running python 3.6 or newer so that all parameter names are keyword-only?
- Does your downstream code expect a plain int or float, or can it handle Decimal and rejected constants?
Where this applies
The size cap and parse hooks only protect the parsing phase. They do not cap nesting depth, string length, or object count inside an already-parsed tree. Very deeply nested structures can still exhaust the C stack or memory; you may need a custom object_pairs_hook for duplicate keys and a separate depth limit. Also, parse_int and parse_float do not affect strings, booleans, or null, and they are not called for non-number literals other than the three constants. The documentation notes that the module itself imposes no limits, so any protection must be added explicitly. In a multi-threaded or microservice context, the byte limit does not prevent a slow loris-style attack that sends bytes gradually; a read timeout and connection limits are separate concerns.