python json 序列化 处理无法序列化的对象

创建日期: 2025-05-28 12:15 | 作者: 风波 | 浏览次数: 2 | 分类: Python

针对一些无法被 json 库序列化的对象,可以使用下面的方式进行规避

import json
from datetime import datetime

def smart_serializer(obj):
    if isinstance(obj, (str, int, float, bool, type(None))):
        return obj 
    elif isinstance(obj, (list, tuple, set)):
        return [smart_serializer(item) for item in obj]
    elif isinstance(obj, dict):
        return {k: smart_serializer(v) for k, v in obj.items()}
    try:
        return json.JSONEncoder().default(obj)
    except TypeError:
        pass
    try:
        return str(obj)
    except:
        pass
    return None

data = { 
    "normal": 123,
    "problematic": datetime.now(),
    "nested": {
        "lambda": lambda x: x,
        "set": {1, 2, 3}
    }   
}

json_str = json.dumps(data, default=smart_serializer)
2 浏览
8 爬虫
0 评论