Movatterモバイル変換


[0]ホーム

URL:


Skip to content
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

JSON Compatible Encoder

There are some cases where you might need to convert a data type (like a Pydantic model) to something compatible with JSON (like adict,list, etc).

For example, if you need to store it in a database.

For that,FastAPI provides ajsonable_encoder() function.

Using thejsonable_encoder

Let's imagine that you have a databasefake_db that only receives JSON compatible data.

For example, it doesn't receivedatetime objects, as those are not compatible with JSON.

So, adatetime object would have to be converted to astr containing the data inISO format.

The same way, this database wouldn't receive a Pydantic model (an object with attributes), only adict.

You can usejsonable_encoder for that.

It receives an object, like a Pydantic model, and returns a JSON compatible version:

fromdatetimeimportdatetimefromfastapiimportFastAPIfromfastapi.encodersimportjsonable_encoderfrompydanticimportBaseModelfake_db={}classItem(BaseModel):title:strtimestamp:datetimedescription:str|None=Noneapp=FastAPI()@app.put("/items/{id}")defupdate_item(id:str,item:Item):json_compatible_item_data=jsonable_encoder(item)fake_db[id]=json_compatible_item_data

In this example, it would convert the Pydantic model to adict, and thedatetime to astr.

The result of calling it is something that can be encoded with the Python standardjson.dumps().

It doesn't return a largestr containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. adict) with values and sub-values that are all compatible with JSON.

Note

jsonable_encoder is actually used byFastAPI internally to convert data. But it is useful in many other scenarios.


[8]ページ先頭

©2009-2026 Movatter.jp