定义方法,当遇到dumps处理不了的方法时,会自动调用这个方法
问题
def test_demo():
data = {
"a": 123,
"b": datetime.now(),
}
print(json.dumps(data))
报错信息
raise TypeError(f'Object of type {o.__class__.__name__} '
f'is not JSON serializable')
E TypeError: Object of type datetime is not JSON serializable
解决方法
def datetime_serializer(obj):
if isinstance(obj, datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
raise TypeError("Type not serializable")
def test_demo():
data = {
"a": 123,
"b": datetime.now(),
}
print(json.dumps(data, default=datetime_serializer))
运行结果
{"a": 123, "b": "2024-02-01 21:39:24"}