Skip to content

model_dump(mode="json") can output non-serializable NaN values #10037

@whao89

Description

@whao89

Initial Checks

  • I confirm that I'm using Pydantic V2

Description

Hi,

See example: I'm expecting that the NaN behavior of model_dump_json() and model_dump(mode="json") to be the same. The dictionary output of model_dump(mode="json") is not strictly JSON serializable. I included the Decimal field as an analogy for the expected behavior.

Thanks!

Example Code

from decimal import Decimal
from pydantic import BaseModel

class M(BaseModel):
    a: float
    b: Decimal

M(a=float("nan"), b=Decimal("12345")).model_dump(mode="json")
#  Out[5]: {'a': nan, 'b': '12345'}

M(a=float("nan"), b=Decimal("12345")).model_dump_json()
#  Out[6]: '{"a":null,"b":"12345"}'

Python, Pydantic & OS Version

pydantic version: 2.8.2
        pydantic-core version: 2.20.1
          pydantic-core build: profile=release pgo=true
                 install path: /home/ubuntu/[redacted]/lib/python3.11/site-packages/pydantic
               python version: 3.11.8 (main, Feb 26 2024, 21:39:34) [GCC 11.2.0]
                     platform: Linux-5.15.0-1066-aws-x86_64-with-glibc2.31
             related packages: typing_extensions-4.12.2 fastapi-0.111.1 mypy-1.11.0
                       commit: unknown

Metadata

Metadata

Assignees

No one assigned

    Labels

    changeSuggested alteration to Pydantic, not a new feature nor a bugtopic-serializationHow Pydantic serializes data, often related to `model_dump`, etc.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions