首页 > 技术文章 > json decimal and datetime

wodekaifalog 2019-05-06 20:48 原文

python json模块默认不能序列化decimal和datetime数据,可以通过自定义一个序列化的类实现:

link: http://www.cnblogs.com/buxizhizhoum/p/7607036.html



import
json import datetime import decimal class SupplementaryEncoder(json.JSONEncoder): def default(self, obj): if isinstance(obj, decimal.Decimal): # for decimal return float(obj) elif isinstance(obj, datetime.datetime): # for datetime return obj.strftime("%Y-%m-%d %H:%M:%S") return json.JSONEncoder.default(self, obj) test_dict = {"a": datetime.datetime.now()} res = json.dumps(test_dict, cls=SupplementaryEncoder)

 

推荐阅读