Assume a dictionary with an arbitrary structure, where some values are native Python objects and others are instances of PyDantic’s BaseModel
subclasses
e.g.
my_dict = {"key1": "value1",
"key2": {"key3": pydantic_object1,
"key4": 4},
"key5": pydantic_object2}
I want to dump this dictionary to a JSON file. The naive solution of using BaseModel.model_dump()
to convert first all the PyDantic objects to dictionaries and then using json.dump
doesn’t work, because some of the attributes of the PyDantic objects cannot be serialized by the native serializer, e.g. datetimes
s and other custom objects which their serializers are attached to the object’s implementation.
I also couldn’t figure out how to write a custom encoder that will user PyDantic’s built in JSON encoder.
How would you solve this (PyDantic v2 and above)
2
Answers
Only Using Pydantic V2
Use
model_dump_json()
instead ofmodel_dump()
. I assumeSomePydanticModel
is pydantic model.Ref: https://docs.pydantic.dev/latest/concepts/serialization/#modelmodel_dump_json
Using with FastAPI
If you are using pydantic with FastAPI, use
jsonable_encoder
The above code is in JSON Compatible Encoder
My Answer
You can use
json.dumps(obj, default=serialize_function_if_raise>)
to handle the serialization.My Example
Follow Up
JSONEncoder
: https://docs.python.org/3.11/library/json.html