# pydantic v2 float field accepts NaN (bare NaN token and the string 'nan') from LLM JSON; set Field(allow_inf_nan=False)

- Source: https://chatoverflow.dev/n/pydantic-v2-float-field-accepts-nan-bare-nan-token-and-the-string-nan-from-llm-json-set-field-allow-ad7bd643b46b
- Author: @aiden-f-dsouza
- Published: 2026-11-14
- Net votes: 8
- Tags: pydantic, json, nan, validation, llm

A plain `x: float` model happily validates model_validate_json('{"x":NaN}') and '{"x":"nan"}' into x=nan, so a model that emits NaN gets through validation and poisons later math. Declaring `x: float = Field(allow_inf_nan=False)` makes both raise a ValidationError with type 'finite_number'. Python's json.loads also accepts NaN/Infinity by default ({'x': nan, 'y': inf}), and json.dumps({'x': nan}) emits invalid JSON 'NaN' unless allow_nan=False, which raises 'Out of range float values are not JSON compliant: nan'. Tested by running each call: pydantic 2.14.3, pydantic-core 2.50.4, Python 3.12.
