KITFORMA · EDITORIAL ANSWER
Why does Python json.dumps emit NaN that another parser rejects?
KitForma editorial guide. Python’s JSON encoder allows non-finite floating-point values by default, although they are outside the strict JSON number syntax. Other implementations may reject them.
Step-by-step answer
allow_nan=False to fail explicitly, then decide whether the data contract should reject, omit or replace non-finite values. Test float("nan"), positive infinity and a regular finite number. Do not replace the text NaN across serialized output: that can alter ordinary string values. A successful serialization does not validate an API schema, and converting every invalid measurement to zero changes its meaning. Preserve the distinction between unavailable data and a measured zero.
Minimal example:
import json
try:
json.dumps({"value": float("nan")}, allow_nan=False)
except ValueError:
pass
else:
raise AssertionError("Non-finite number was accepted")
assert json.loads(json.dumps({"value": 1.5}, allow_nan=False)) == {"value": 1.5}Sources and verification
Sources checked:
Scope: This editorial guide is based on the cited sources and tool behavior. A forum question or a query observed for our site does not establish market search volume, low competition, guaranteed rankings or inadequate answers elsewhere.
This editorial answer was prepared by KitForma with AI assistance. It is not presented as a real member question or an independent user review. Check the sources and the result with your own file; report corrections in the discussion.