Pydantic Convert To Jsonable Dict (not Full Json String)
Solution 1:
The current version of pydantic
does not support creating jsonable dict
straightforwardly. But you can use the following trick:
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())
Solution 2:
it appears this functionality has been proposed, and (may be) favored by pydantic's author samuel colvin, as https://github.com/samuelcolvin/pydantic/issues/951#issuecomment-552463606
which proposes adding a simplify
parameter to Model.dict()
to output jsonalbe data.
This code runs in a production api layer, and is exersized such that we can't use the one-line workaround suggested (just doing a full serialize (.json()
) + full deserialize). We implemented a custom function to do this, descending the result of .dict()
and converting types to jsonable - hopefully the above proposed functionality is added to pydantic in the future.
Solution 3:
Another alternative is to use the jsonable_encoder
method from fastapi
if you're using that already: https://fastapi.tiangolo.com/tutorial/encoder/
The code seems pretty self-contained so you could copy paste it if the license allows it.
Post a Comment for "Pydantic Convert To Jsonable Dict (not Full Json String)"