def _json_default_exact(obj):
"""Serialization handlers for types unsupported by `simplejson`
that try to preserve the exact data types.
"""
classname = type(obj).__name__
handlers = {
'datetime': methodcaller('isoformat'),
'date': methodcaller('isoformat'),
'time': methodcaller('isoformat'),
'timedelta': partial(getattrs, attrs=['days', 'seconds', 'microseconds']),
'tuple': list,
'set': list,
'frozenset': list,
'complex': partial(getattrs, attrs=['real', 'imag']),
'Decimal': str,
'Fraction': partial(getattrs, attrs=['numerator', 'denominator']),
'UUID': partial(getattrs, attrs=['hex']),
}
if classname in handlers:
return {"__class__": classname,
"__value__": handlers[classname](obj)}
elif isinstance(obj, tuple) and classname != 'tuple':
return {"__class__": "namedtuple",
"__value__": _dump_namedtuple(classname, obj)}
raise TypeError(repr(obj) + " is not JSON serializable")
评论列表
文章目录