TypeError: datetime.datetime(2016, 9, 25, 21, 12, 19, 135649) is not JSON serializable解决办法

时间:2022-10-26 10:57:29

1.一个简单的方法来修补json模块,这样序列将支持日期时间。

        import json
import datetime json.JSONEncoder.default = lambda self, obj: (obj.isoformat() if isinstance(obj, datetime.datetime) else None) result = json.dumps(ret)
print(result)

  

[{"date": "2016-09-25T21:12:19.135649", "id": 16}]

2.该模块为您提供了一个默认的编码器:json.JSONEncoder。您需要扩展这个提供您的实现default方法序列化对象。

        import json
import datetime
from time import mktime
#
# class MyEncoder(json.JSONEncoder):
# def default(self, obj):
# if isinstance(obj, datetime.datetime):
# return str(mktime(obj.timetuple()))
#
# return json.JSONEncoder.default(self, obj)
# result = json.dumps(ret, cls = MyEncoder)

  

[{"date": "1474809139.0", "id": 16}]

  

方法3:我最喜欢的, 同时可以更好的应用于tornado的序列格式化

TypeError: datetime.datetime(2016, 9, 25, 21, 12, 19, 135649) is not JSON serializable解决办法

解决办法:

from decimal import Decimal
import datetime, json class ComplexEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.strftime("%Y-%m-%d %H:%M:%S")
elif isinstance(obj, Decimal):
return str(obj)
else:
# return json.JSONEncoder.default(self, obj)
       return str(obj) # 根据需求进行修改 if __name__ == '__main__': data = [{"ProjectName": "测试", "UserID": datetime.datetime.now(), "ProjectCreateTime": "2017-12-18 15:15", "ProjectPublic": "",
"ProjectOrgan": Decimal()}]
print(data)
print(json.dumps(data, cls=ComplexEncoder, ensure_ascii=False))

TypeError: datetime.datetime(2016, 9, 25, 21, 12, 19, 135649) is not JSON serializable解决办法

            res = SelectProInfor(UserID)
for i in res:
print(i)
for k, va in i.items():
if isinstance(va, decimal.Decimal):
i[k] = str(va)
if isinstance(va, object):
i[k] = str(va)