Files
hsa/Html/apps/_docs/json_serializer_usage.md
2025-12-10 15:10:37 +08:00

2.7 KiB
Raw Permalink Blame History

JSON Serializer 用法文档

概述

json_serializer 是一个通用的JSON序列化工具用于处理Python中常见的非JSON序列化类型datetimedatetimeObjectId等。

支持的类型

  • 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

函数说明

  1. json_serialize(obj): 将对象序列化为JSON字符串

    • 参数: obj - 要序列化的对象
    • 返回: JSON字符串
  2. json_serialize_dict(obj): 将对象转换为可JSON序列化的字典

    • 参数: obj - 要序列化的对象
    • 返回: 可JSON序列化的字典
  3. 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"}

应用场景

  1. API请求中的数据序列化
  2. 保存数据到文件或数据库
  3. 跨服务数据传输
  4. 日志记录中的复杂对象序列化

注意事项

  • 对于自定义对象,会尝试序列化其__dict__属性
  • 对于无法序列化的类型,会转换为字符串表示
  • 确保导入路径正确,特别是在不同模块中使用时