You can add the 'default' parameter to json.dumps to handle this:(您可以将'default'参数添加到json.dumps来处理:)
date_handler = lambda obj: (
obj.isoformat()
if isinstance(obj, (datetime.datetime, datetime.date))
else None
)
json.dumps(datetime.datetime.now(), default=date_handler)
'"2010-04-20T20:08:21.634121"'
Which is ISO 8601 format.(这是ISO 8601格式。)
A more comprehensive default handler function:(更全面的默认处理函数:)
def handler(obj):
if hasattr(obj, 'isoformat'):
return obj.isoformat()
elif isinstance(obj, ...):
return ...
else:
raise TypeError, 'Object of type %s with value of %s is not JSON serializable' % (type(obj), repr(obj))
Update: Added output of type as well as value.(更新:添加了类型和值的输出。)
Update: Also handle date(更新:还处理日期) 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…