Pydantic 1.x (old answer)
The current version of pydantic
does not support creating jsonable dict
straightforwardly. But you can use the following trick:
Note: This is a suboptimal solution
class Model(BaseModel):
the_id: UUID = Field(default_factory=uuid4)
print(json.loads(Model().json()))
{'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}
Or more efficiently by means of orjson
orjson.loads(Model().json())
Pydantic 2
There is model_dump()
method accepting mode
parameter.
mode: Literal['json', 'python'] | str="python"
If mode is ‘json’, the dictionary will only contain JSON serializable types.
If mode is ‘python’, the dictionary may contain any Python objects.
class Model(BaseModel):
the_id: UUID = Field(default_factory=uuid4)
print(Model().model_dump(mode="json"))
# {'the_id': '4c94e7bc-78fe-48ea-8c3b-83c180437774'}