-
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
model_dump(mode="json")
can output non-serializable NaN values
#10037
Comments
Thanks for reporting this. This does look inconsistent - probably a good first issue for someone looking to dig into |
@sydney-runkle can you please help me figuring out what could go wrong with the #10102 . |
|
Interesting.. I tried model_dump = M(a=float("nan"), b=Decimal("12345")).model_dump(mode="json")
json.dumps(model_dump) and I see: '{"a": NaN, "b": "12345"}' This is definitely different from the second output in Haven't worked with |
after more exploration in the linked issue above, this is currently how one could get the desired behavior @whao89 expects: from pydantic import BaseModel, ConfigDict
import math
class M(BaseModel):
model_config = ConfigDict(
ser_json_inf_nan = "constants"
)
a: float
M(a=float("nan")).model_dump(mode="json") # {'a': nan}
M(a=float("nan")).model_dump_json() # '{"a":NaN}'
j = json.loads(M(a=float("nan")).model_dump_json())
assert math.isnan(j['a'])
j = M(a=float("nan")).model_dump(mode="json")
assert math.isnan(j['a']) |
If I recall correctly, in pydantic/pydantic-core#1062 I added the "constants" mode of Similarly, it would be a breaking change for IMO this is a sad situation where we need to wait for V3, and in V3:
|
Initial Checks
Description
Hi,
See example: I'm expecting that the NaN behavior of
model_dump_json()
andmodel_dump(mode="json")
to be the same. The dictionary output ofmodel_dump(mode="json")
is not strictly JSON serializable. I included theDecimal
field as an analogy for the expected behavior.Thanks!
Example Code
Python, Pydantic & OS Version
The text was updated successfully, but these errors were encountered: