Safely parsing model JSON responses with size and number controls
Limit input size and number types when decoding untrusted model JSON to prevent resource exhaustion and malformed numbers. Use Python json with bounded input and custom parse_int, parse_float, and parse_constant hooks.
On this page
Key idea
Bind the raw response length before decoding, reject non-finite constants, and wrap json.loads in typed numeric hooks so oversized or malformed model responses fail fast instead of exhausting CPU or memory.
Practical tips for safely parsing model JSON responses
Model responses are untrusted input even when they arrive over an internal API. The Python json module warns that a malicious JSON string can make the decoder consume substantial CPU and memory, so parsing without bounds is a denial-of-service risk. Before decoding, treat the raw response as a byte or string buffer whose length must be checked, and treat every number as a potential type confusion or overflow vector. Python 3.11 helps by limiting integer string length during conversion, but older releases and custom decoders still need explicit guards. This article shows how to bound input size, restrict numeric decoding, and handle errors without exposing internal state. Do not rely on the response Content-Type header; an attacker can label arbitrary text as application/json.
Check input size
Check the length of the raw JSON document before calling json.loads or json.load. The module accepts str, bytes, and bytearray, and the input encoding must be UTF-8, UTF-16, or UTF-32. If the payload exceeds your configured cap, reject it with a generic error rather than decoding partially; JSON is not a framed protocol, so a truncated document is invalid and should not be repaired by the caller. Choose a cap based on the largest legitimate model response, not on available memory, because an attacker can send many moderately large documents in parallel. For streaming sources, read into a bounded buffer first and only decode when the complete document fits the cap.
Control number types
Control number types through parse_int, parse_float, and parse_constant. parse_int receives the integer text and can reject overly long strings or convert to a bounded type; parse_float does the same for real numbers. parse_constant is invoked for NaN, Infinity, and -Infinity, which Python accepts by default although they are outside RFC 7159. A hook that raises ValueError for these constants prevents non-standard numbers from reaching application logic. In Python 3.11, the default parse_int already applies the interpreter's integer string conversion length limit, but an explicit hook gives a clearer error message and works consistently across versions. Separate precision from false-positive workload: a strict numeric hook may reject valid scientific notation if your parser is too narrow, so test with boundary values such as 1e400 and 123456789012345678901234567890.
Use safe decoding methods
Use json.loads inside a try block and catch JSONDecodeError, which reports the document, position, line, and column of the failure. Keep strict at its default True so control characters inside strings are rejected. After decoding, validate the resulting object against a schema or expected shape; the decoder itself only enforces JSON syntax, not required fields or value ranges. Do not use eval or ast.literal_eval on JSON text, because they execute Python syntax and introduce injection risks. Structural checks such as required keys are business rules, while JSONDecodeError is a structural failure; keep them in separate layers.
import json
from json import JSONDecodeError
MAX_INPUT_BYTES = 64 * 1024
def safe_int(text):
if len(text) > 20:
raise ValueError("integer text too long")
return int(text)
def safe_float(text):
value = float(text)
if value != value or value in (float("inf"), float("-inf")):
raise ValueError("non-finite float rejected")
return value
def reject_constant(constant):
raise ValueError(f"non-standard constant {constant!r} rejected")
def parse_model_json(raw):
if isinstance(raw, (bytes, bytearray)):
if len(raw) > MAX_INPUT_BYTES:
raise ValueError("input exceeds size limit")
text = raw.decode("utf-8")
else:
if len(raw) > MAX_INPUT_BYTES:
raise ValueError("input exceeds size limit")
text = raw
return json.loads(
text,
parse_int=safe_int,
parse_float=safe_float,
parse_constant=reject_constant,
)
sample = '{"answer": 42, "score": 3.14, "note": "ok"}'
result = parse_model_json(sample)
print(result)Applicability
- Is the model response coming from an untrusted or potentially malicious source?
- Do you need to reject integers longer than your application can safely handle?
- Are NaN, Infinity, or -Infinity acceptable in your domain, or should they be rejected as non-JSON?
- Can your service afford to reject oversized payloads before decoding?
- Are you running Python 3.11 or later to use the built-in integer string length limit?
Where this applies
Size caps reject legitimate large payloads, numeric hooks add per-token overhead, and JSON syntax validation does not enforce required fields, value ranges, or recursion depth; combine these controls with schema validation and memory budgets.