fastapi: pydantic模型、字典、json字符串的相互转换
一,用到的方法
核心转换方法总结
-
Pydantic 模型 ➔ Python 字典:
model.model_dump() -
Pydantic 模型 ➔ JSON 字符串:
model.model_dump_json() -
JSON 字符串 ➔ Pydantic 模型:
Model.model_validate_json(json_str) -
Python 字典 ➔ Pydantic 模型:
Model.model_validate(dict_data) -
JSON 字符串 ➔ Python 字典:标准库
json.loads(json_str) -
Python 字典 ➔ JSON 字符串:标准库
json.dumps(dict_data)
二,代码:
# 1. 定义 Pydantic 模型
class Item(BaseModel):
id: int
name: str
price: float
tags: List[str] = []
description: Optional[str] = None
@router.get("/trans", summary="演示字典和模型的互相转换")
async def get_trans(request: Request):
# 初始化一个 Pydantic 模型实例用于测试
item_model = Item(
id=1,
name="智能手机",
price=4999.0,
tags=["电子产品", "数码"],
description="最新款旗舰机"
)
print("--- 初始 Pydantic 模型实例 ---")
print(f"类型: {type(item_model)}")
print(f"数据: {item_model}\n")
# ==========================================
# 转换方向 1:Pydantic 模型 ➔ Python 字典 & JSON
# ==========================================
# 1.1 Pydantic 模型转 Python 字典
item_dict = item_model.model_dump()
print("--- 1.1 Pydantic 模型 -> Python 字典 ---")
print(f"类型: {type(item_dict)}")
print(f"数据: {item_dict}\n")
# 1.2 Pydantic 模型转 JSON 字符串
item_json_from_model = item_model.model_dump_json()
print("--- 1.2 Pydantic 模型 -> JSON 字符串 ---")
print(f"类型: {type(item_json_from_model)}")
print(f"数据: {item_json_from_model}\n")
# ==========================================
# 转换方向 2:Python 字典 ➔ JSON & Pydantic 模型
# ==========================================
# 2.1 Python 字典转 JSON 字符串 (使用 Python 标准库)
item_json_from_dict = json.dumps(item_dict, ensure_ascii=False)
print("--- 2.1 Python 字典 -> JSON 字符串 ---")
print(f"类型: {type(item_json_from_dict)}")
print(f"数据: {item_json_from_dict}\n")
# 2.2 Python 字典转 Pydantic 模型
new_model_from_dict = Item.model_validate(item_dict)
print("--- 2.2 Python 字典 -> Pydantic 模型 ---")
print(f"类型: {type(new_model_from_dict)}")
print(f"数据: {new_model_from_dict}\n")
# ==========================================
# 转换方向 3:JSON 字符串 ➔ Pydantic 模型 & Python 字典
# ==========================================
# 准备一个 JSON 字符串
json_string = '{"id": 2, "name": "无线耳机", "price": 799.5, "tags": ["音频"], "description": null}'
# 3.1 JSON 字符串转 Pydantic 模型
new_model_from_json = Item.model_validate_json(json_string)
print("--- 3.1 JSON 字符串 -> Pydantic 模型 ---")
print(f"类型: {type(new_model_from_json)}")
print(f"数据: {new_model_from_json}\n")
# 3.2 JSON 字符串转 Python 字典 (使用 Python 标准库)
new_dict_from_json = json.loads(json_string)
print("--- 3.2 JSON 字符串 -> Python 字典 ---")
print(f"类型: {type(new_dict_from_json)}")
print(f"数据: {new_dict_from_json}\n")
三,测试效果:

浙公网安备 33010602011771号