Skip to content
AITroveRead. Build. Understand.
Make this comfortable

Python JSON nonfinite numbers: reject NaN on input and output

Last updated: 1 Oct 20264 min read
tutorial
IntermediateBy AITrove Editorial

Python's json defaults can accept or emit NaN and infinity, so a strict wire boundary needs explicit checks.

Download Python source kit

Operation contract

A risk-score service receives a payload containing NaN. Python accepts that token by default even though it is outside strict JSON number grammar. The parse_constant hook rejects it. On output, allow_nan=False prevents the service from emitting a nonfinite float. Duplicate object names are another decoder policy and require their own check.

Failure and ownership boundary

The hook does not validate numeric ranges, nesting depth or application schema. Enforce a byte budget before parsing an untrusted body. For exact decimal money, choose a decimal representation and a deliberate serialization format rather than relying on binary float conversion.

Working program

python
import json

def reject_nonfinite(token):
    raise ValueError("nonfinite number: " + token)

try:
    json.loads('{"risk": NaN}', parse_constant=reject_nonfinite)
except ValueError as error:
    print(error)

print("accepted:", json.loads('{"risk": 47}')["risk"])
try:
    json.dumps({"risk": float("nan")}, allow_nan=False)
except ValueError:
    print("nonfinite output rejected")

Output

Output
nonfinite number: NaN
accepted: 47
nonfinite output rejected

Costs and limits

The token check is small relative to parsing. Input bytes and nesting still need separate limits.

Common Mistakes

  • Do not assume the default parser rejects NaN.
  • Do not emit nonfinite floats into a strict JSON API.
  • A nonfinite check is not a complete schema validator.

Connected lessons

Python JSON duplicate keys: reject ambiguous object fields, Python JSON validation: reject duplicate members and non-integer amounts, Python Decimal money: parse decimal text and choose rounding explicitly.

Test this contract in the Python I/O and algorithm boundary quiz.

python
json-nonfinite-number-boundary
Storage details