针对一些无法被 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)