跳到内容

JSON 兼容的编码器

在某些情况下,您可能需要将一种数据类型(例如 Pydantic 模型)转换为与 JSON 兼容的类型(例如 dictlist 等)。

例如,当您需要将其存储在数据库中时。

为此,FastAPI 提供了一个 jsonable_encoder() 函数。

使用 jsonable_encoder

假设您有一个数据库 fake_db,它只接收与 JSON 兼容的数据。

例如,它不接收 datetime 对象,因为这些对象与 JSON 不兼容。

因此,datetime 对象必须转换为包含 ISO 格式 数据的 str

同理,这个数据库不会接收 Pydantic 模型(一个带有属性的对象),而只会接收 dict

您可以使用 jsonable_encoder 来完成此操作。

它接收一个对象,例如 Pydantic 模型,并返回一个与 JSON 兼容的版本。

from datetime import datetime

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

fake_db = {}


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: str | None = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    fake_db[id] = json_compatible_item_data
🤓 其他版本和变体
from datetime import datetime
from typing import Union

from fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel

fake_db = {}


class Item(BaseModel):
    title: str
    timestamp: datetime
    description: Union[str, None] = None


app = FastAPI()


@app.put("/items/{id}")
def update_item(id: str, item: Item):
    json_compatible_item_data = jsonable_encoder(item)
    fake_db[id] = json_compatible_item_data

在此示例中,它会将 Pydantic 模型转换为 dict,并将 datetime 转换为 str

调用它的结果是可以用 Python 标准的 json.dumps() 进行编码的东西。

它不会返回一个包含 JSON 格式数据的大 str(作为字符串)。它返回一个 Python 标准数据结构(例如 dict),其值和子值都与 JSON 兼容。

注意

FastAPI 内部实际上使用 jsonable_encoder 来转换数据。但它在许多其他场景中也很有用。