9. fastApi的json编码器使用示例_fastapi json

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 fastapi import FastAPI
from fastapi.encoders import jsonable_encoder
from pydantic import BaseModel
import pymongo

client = pymongo.MongoClient("mongodb://192.168.10.230:27017/")
myset = client['test']['demo']  # 将数据存入mongodb


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)
    # 将datetime转换为str
    print(type(json_compatible_item_data)) # <class 'dict'>
    print("===================================>开始插入数据")
    myset.insert_one(json_compatible_item_data)
    print("===================================>插入数据完成")
    return json_compatible_item_data["title"]

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30

以上代码 把Pydantic 模型转换为字典,并把 datetime 转换为字符串jsonable_encoder 函数返回的不是包含 JSON 数据的长字符串,而是返回值与子值都兼容 JSON 的 Python 标准数据结构,比如字典