FastAPI 教程翻译 - 用户指南 23 - JSON 兼容编码器
FastAPI Tutorial - User Guide - 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 a dict
, list
, etc).
在某些情况下,您可能需要将数据类型(例如 Pydantic 模型)转换为与 JSON 兼容的数据(例如 dict
、list
等)。
For example, if you need to store it in a database.
例如,如果您需要将其存储在数据库中。
For that, FastAPI provides a jsonable_encoder()
function.
为此,FastAPI 提供了一个 jsonable_encoder()
函数。
Using the jsonable_encoder
使用 jsonable_encoder
Let’s imagine that you have a database fake_db
that only receives JSON compatible data.
假设您有一个仅接收 JSON 兼容数据的数据库 fake_db
。
For example, it doesn’t receive datetime
objects, as those are not compatible with JSON.
例如,它不接收 datetime
对象,因为它们与 JSON 不兼容。
So, a datetime
object would have to be converted to a str
containing the data in ISO format.
因此,datetime
对象必须转换为包含 ISO格式 数据的 str
。
The same way, this database wouldn’t receive a Pydantic model (an object with attributes), only a dict
.
同样,该数据库将不会接收 Pydantic 模型(具有属性的对象),而只会接收 dict
。
You can use jsonable_encoder
for that.
您可以使用 jsonable_encoder
。
It receives an object, like a Pydantic model, and returns a JSON compatible version:
它接收一个对象,例如 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
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
In this example, it would convert the Pydantic model to a dict
, and the datetime
to a str
.
在这个例子中,它将 Pydantic 模型转换为 dict
,将 datetime 转换为 str
。
The result of calling it is something that can be encoded with the Python standard json.dumps()
.
调用它的结果是可以使用 Python 标准 json.dumps()
进行编码的东西。
It doesn’t return a large str
containing the data in JSON format (as a string). It returns a Python standard data structure (e.g. a dict
) with values and sub-values that are all compatible with JSON.
它不会返回包含 JSON 格式数据(字符串形式)的大型 str
。它会返回 Python 标准数据结构(例如 dict
),其值和子值都与 JSON 兼容。
Note
注意
jsonable_encoder
is actually used by FastAPI internally to convert data. But it is useful in many other scenarios.
jsonable_encoder
实际上由 FastAPI 内部使用以转换数据。但这在许多其他情况下很有用。