1. 程式人生 > >json decimal and datetime

json decimal and datetime

return get htm one ima ins pre itl 序列化

python json模塊默認不能序列化decimal和datetime數據,可以通過自定義一個序列化的類實現:

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

import json
import datetime


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)

json decimal and datetime