2.7 KiB
2.7 KiB
JSON Serializer 用法文档
概述
json_serializer 是一个通用的JSON序列化工具,用于处理Python中常见的非JSON序列化类型,如datetime、date、time、ObjectId等。
支持的类型
datetime: 转换为ISO格式字符串date: 转换为ISO格式字符串time: 转换为ISO格式字符串ObjectId: 转换为字符串bytes: 转换为UTF-8字符串set/frozenset: 转换为列表- 其他不可序列化类型: 转换为字符串表示
安装位置
位于 apps/utils/json_serializer.py
使用方法
导入
from apps.utils.json_serializer import json_serialize, json_serialize_dict, JSONEncoder
函数说明
-
json_serialize(obj): 将对象序列化为JSON字符串
- 参数:
obj- 要序列化的对象 - 返回: JSON字符串
- 参数:
-
json_serialize_dict(obj): 将对象转换为可JSON序列化的字典
- 参数:
obj- 要序列化的对象 - 返回: 可JSON序列化的字典
- 参数:
-
JSONEncoder: 自定义JSON编码器类,可直接用于
json.dumps()
示例
基本使用
from datetime import datetime
from apps.utils.json_serializer import json_serialize_dict
# 创建包含datetime的字典
data = {
"user_id": "test_user",
"updated_at": datetime.now(),
"scores": [85, 90, 95]
}
# 序列化
serialized = json_serialize_dict(data)
print(serialized)
# 输出: {"user_id": "test_user", "updated_at": "2025-12-10T15:30:45.123456", "scores": [85, 90, 95]}
在API请求中使用
import requests
from apps.utils.json_serializer import json_serialize_dict
# 准备请求数据
data = {
"user_id": "test_user",
"updated_at": datetime.now(),
"progress": {"chapter1": "completed", "chapter2": "in_progress"}
}
# 序列化数据
serialized_data = json_serialize_dict(data)
# 发送请求
response = requests.post(
"https://api.example.com/upload",
json=serialized_data,
headers={"Content-Type": "application/json"}
)
直接使用JSONEncoder
import json
from datetime import datetime
from apps.utils.json_serializer import JSONEncoder
# 创建数据
data = {"updated_at": datetime.now()}
# 使用自定义编码器
json_str = json.dumps(data, cls=JSONEncoder, ensure_ascii=False)
print(json_str)
# 输出: {"updated_at": "2025-12-10T15:30:45.123456"}
应用场景
- API请求中的数据序列化
- 保存数据到文件或数据库
- 跨服务数据传输
- 日志记录中的复杂对象序列化
注意事项
- 对于自定义对象,会尝试序列化其
__dict__属性 - 对于无法序列化的类型,会转换为字符串表示
- 确保导入路径正确,特别是在不同模块中使用时