[英]Logging dictionaries with datetime objects without Serialization error
I'm trying to log python dictionary as JSON like so logging.info(dict(msg="foo", data=obj))
.我正在尝试将 python 字典记录为 JSON,就像这样
logging.info(dict(msg="foo", data=obj))
。 However in some cases, obj
may contain datetime objects and in those cases I get a JSON serialization error.但是在某些情况下,
obj
可能包含日期时间对象,在这些情况下我会收到 JSON 序列化错误。
Is there a simple way to log dictionaries where objects (such as datetime objects) are serialized automatically, such as having it call the "str" function on these objects?是否有一种简单的方法来记录对象(例如日期时间对象)自动序列化的字典,例如让它在这些对象上调用“str”函数?
You may define your own serializer for datetime
object:您可以为
datetime
对象定义自己的序列化程序:
def to_json(python_object):
if isinstance(python_object, datetime.datetime):
return {'__class__': 'datetime.datetime',
'__value__': time.asctime(python_object.timetuple())}
if isinstance(python_object, time.struct_time):
return {'__class__': 'time.asctime',
'__value__': time.asctime(python_object)}
if isinstance(python_object, bytes):
return {'__class__': 'bytes',
'__value__': list(python_object)}
raise TypeError(repr(python_object) + ' is not JSON serializable')
def from_json(json_object):
if '__class__' in json_object:
if json_object['__class__'] == 'datetime.datetime':
return datetime.datetime.fromtimestamp(time.mktime(time.strptime(json_object['__value__'])))
if json_object['__class__'] == 'time.asctime':
return time.strptime(json_object['__value__'])
if json_object['__class__'] == 'bytes':
return bytes(json_object['__value__'])
return json_object
and then call it this way:然后这样称呼它:
json.dump(entry, f, default=to_json)
or for reading back或者为了回读
entry = json.load(f, object_hook=from_json)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.