Reliable JSON Parsing of Model Responses: How allow_nan and parse_constant Affect External Parser Compatibility
Python's json module silently emits NaN and Infinity tokens that violate RFC 7159, breaking strict external parsers. Setting allow_nan=False and parse_constant enforces compliance on both serializer and deserializer sides.
On this page
Key idea
The json.dumps default (allow_nan=True) produces bare NaN, Infinity, and -Infinity tokens that are not valid JSON per RFC 7159. Use allow_nan=False to raise ValueError on the serializer side, and parse_constant to reject or remap these tokens on the deserializer side. Both guards must be set independently because each only protects one direction of the pipeline.
Default Python JSON behavior produces non-compliant output
The Python json module, by default, encodes float('nan') as the bare token NaN and float('inf') as Infinity. The official documentation states plainly: "The RFC does not permit the representation of infinite or NaN number values. Despite that, by default, this module accepts and outputs Infinity, -Infinity, and NaN as if they were valid JSON number literal values." These tokens are not quoted strings; they appear as unquoted identifiers in the output, which no RFC 7159 or RFC 8259 compliant parser will accept. A JavaScript JSON.parse call, a PostgreSQL JSON column, or a JSON Schema validator will reject such text outright. The danger is that the failure is silent at serialization time and only manifests downstream, often in a different service or language runtime, making the root cause hard to trace.
This behavior is documented as intentional for round-trip convenience within Python, but it creates a compatibility cliff the moment the serialized text crosses a language boundary.
import json
# Default: produces invalid JSON silently
bad = json.dumps({"score": float("nan"), "limit": float("inf")})
print(bad) # {"score": NaN, "limit": Infinity} -- not valid JSONTrade-off between internal round-trip convenience and cross-language interoperability
The Python documentation explains the rationale: "If allow_nan is true (the default), then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders." The module's default settings also produce output that is a subset of YAML 1.0 and 1.1, reinforcing the design choice toward lenient round-tripping within the Python ecosystem.
However, this convenience becomes a reliability risk in production pipelines. A model response containing a division-by-zero result produces float('inf'), which json.dumps happily serializes as the bare token Infinity. If that response is stored in a database JSON column, forwarded to a JavaScript frontend, or validated against a JSON Schema that declares "type": "number", the downstream consumer fails. The JSON Schema specification for objects requires that property values conform to their declared types, and NaN or Infinity is not a valid JSON number literal, so a schema validator will flag the document as non-compliant before type checking even begins.
Enforcing strict compliance with allow_nan and parse_constant
On the serializer side, passing allow_nan=False to json.dumps causes a ValueError with the message "Out of range float values are not JSON compliant" whenever a NaN, Infinity, or -Infinity value is encountered. This converts a silent compatibility violation into an immediate, locatable error at the point of serialization.
On the deserializer side, parse_constant accepts a callable that is invoked with the string name of each non-standard constant token ("NaN", "Infinity", "-Infinity"). The callable's return value replaces the token in the decoded result. You can return None, raise an exception, or map to a sentinel. The documentation notes that parse_constant is not called on null, true, or false, only on these three special tokens. Both guards must be set independently: allow_nan=False only protects the serializer, while a malicious or buggy external producer can still send NaN tokens that bypass it entirely.
The minimum Python version for keyword-only arguments on json.dumps and json.loads is 3.6.
import json
# Strict serializer: raises immediately on out-of-range floats
try:
json.dumps({"score": float("nan")}, allow_nan=False)
except ValueError as e:
print(e) # Out of range float values are not JSON compliant
# Strict deserializer: reject or map NaN/Infinity tokens
result = json.loads('{"score": NaN}', parse_constant=lambda x: None)
print(result) # {'score': None}When the default is acceptable and when it is not
The default round-trip is functionally correct when both the producer and consumer are Python processes and the serialized text never leaves the process boundary. In that narrow case, json.loads(json.dumps(float('nan'))) returns float('nan'), and no external system ever sees the non-compliant token.
The risk appears the moment the output feeds a JavaScript runtime, a JSON Schema validator, a database JSON column, an HTTP API consumed by another language, or any RFC-strict parser. In model-response pipelines, this boundary is crossed frequently: an LLM returns a JSON object, a backend service parses it, stores it, and forwards it to a frontend. If any hop uses a strict parser, the non-compliant token causes a failure that is difficult to diagnose because the producing code raised no error.
This guidance does not address duplicate keys (use object_pairs_hook) or structural validation (use a JSON Schema validator such as jsonschema). Those are orthogonal concerns that require separate mechanisms.
Applicability
- Is the serialized JSON text ever consumed by a non-Python parser, stored in a database JSON column, or validated against a JSON Schema?
- Do both the serializer and deserializer sides of the pipeline independently enforce compliance, or is only one side guarded?
- Are there code paths that produce float('nan') or float('inf') from arithmetic operations (division by zero, overflow) that could leak into model response payloads?
- Does the deployment environment use Python 3.6 or later, where keyword-only arguments are available on json.dumps and json.loads?
Where this applies
allow_nan=False only guards the serializer; an external producer can still send NaN tokens, so parse_constant must be set independently on the deserializer side. parse_constant is not called on null, true, or false, only on NaN, Infinity, and -Infinity. This article does not cover duplicate-key handling (object_pairs_hook) or full structural validation (JSON Schema). The default round-trip remains functionally correct when text never leaves the Python process boundary.