跳转至

JSON 编码器

有时,我们要把 Pydantic 模型等数据类型转换为字典列表等与 JSON 兼容的格式。

例如, 把 Pydantic 模型存入数据库时就要进行转换。

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

使用 jsonable_encoder

假设数据库 fake_db 只接收与 JSON 兼容的数据。

该数据库不能接收与 JSON 不兼容的 datetime 对象。

因此必须把 datetime 对象转换为包含 ISO 格式数据的字符串

同理,该数据库也不能接收 Pydantic 模型(带属性的对象),只能接收字典

接收 Pydantic 模型要使用 jsonable_encoder

jsonable_encoder 函数接收 Pydantic 模型等对象,然后返回兼容 JSON 的数据:

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

本例把 Pydantic 模型转换为字典,并把 datetime 转换为字符串

该函数的输出结果可以用 Python 的 json.dumps() 编码。

jsonable_encoder 函数返回的不是包含 JSON 数据的长字符串,而是返回值与子值都兼容 JSON 的 Python 标准数据结构,比如字典

笔记

虽然,jsonable_encoder 用于在 FastAPI 内部转换数据,但在其他场景下也可以使用。