pydantic convert to jsonable dict (not full json string)

We Are Going To Discuss About pydantic convert to jsonable dict (not full json string). So lets Start this Python Article.

pydantic convert to jsonable dict (not full json string)

  1. How to solve pydantic convert to jsonable dict (not full json string)

    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())

  2. pydantic convert to jsonable dict (not full json string)

    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 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())

Original Author alex_noname Of This Content

Solution 2

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.

Original Author aiguofer Of This Content

Solution 3

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.

Original Author aiguofer Of This Content

Conclusion

So This is all About This Tutorial. Hope This Tutorial Helped You. Thank You.

Also Read,

ittutorial team

I am an Information Technology Engineer. I have Completed my MCA And I have 4 Year Plus Experience, I am a web developer with knowledge of multiple back-end platforms Like PHP, Node.js, Python and frontend JavaScript frameworks Like Angular, React, and Vue.

Leave a Comment