我为我的项目制作了自己的课程:
import datetime
import decimal
import json
import sys
class EnhancedJSONEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
ARGS = ('year', 'month', 'day', 'hour', 'minute',
'second', 'microsecond')
return {'__type__': 'datetime.datetime',
'args': [getattr(obj, a) for a in ARGS]}
elif isinstance(obj, datetime.date):
ARGS = ('year', 'month', 'day')
return {'__type__': 'datetime.date',
'args': [getattr(obj, a) for a in ARGS]}
elif isinstance(obj, datetime.time):
ARGS = ('hour', 'minute', 'second', 'microsecond')
return {'__type__': 'datetime.time',
'args': [getattr(obj, a) for a in ARGS]}
elif isinstance(obj, datetime.timedelta):
ARGS = ('days', 'seconds', 'microseconds')
return {'__type__': 'datetime.timedelta',
'args': [getattr(obj, a) for a in ARGS]}
elif isinstance(obj, decimal.Decimal):
return {'__type__': 'decimal.Decimal',
'args': [str(obj),]}
else:
return super().default(obj)
class EnhancedJSONDecoder(json.JSONDecoder):
def __init__(self, *args, **kwargs):
super().__init__(*args, object_hook=self.object_hook,
**kwargs)
def object_hook(self, d):
if '__type__' not in d:
return d
o = sys.modules[__name__]
for e in d['__type__'].split('.'):
o = getattr(o, e)
args, kwargs = d.get('args', ()), d.get('kwargs', {})
return o(*args, **kwargs)
if __name__ == '__main__':
j1 = json.dumps({'now': datetime.datetime.now(),
'val': decimal.Decimal('9.3456789098765434987654567')},
cls=EnhancedJSONEncoder)
print(j1)
o1 = json.loads(j1, cls=EnhancedJSONDecoder)
print(o1)
结果:
{"val": {"args": ["9.3456789098765434987654567"], "__type__": "decimal.Decimal"}, "now": {"args": [2014, 4, 29, 11, 44, 57, 971600], "__type__": "datetime.datetime"}}
{'val': Decimal('9.3456789098765434987654567'), 'now': datetime.datetime(2014, 4, 29, 11, 44, 57, 971600)}
参考:
__init__()
注意:通过将类型作为键和 args、kwargs 作为值的自定义字典传递给编码器并在方法中使用它(或默认字典),可以使其更加灵活default()
。