Python JSON编码器支持datetime? [英] Python JSON encoder to support datetime?
问题描述
有没有优雅的方法让Python JSON编码器支持日期时间?一些第三方模块或简单的黑客?
is there any elegant way to make Python JSON encoder support datetime? some 3rd party module or easy hack?
我正在使用tornado的数据库包装器从db获取一些原始数据以生成一个json。查询结果包括一个常规的MySQL时间戳列。
I am using tornado's database wrapper to fetch some raws from db to generate a json. The query result includes a regular MySQL timestamp column.
Python的默认json编码器不支持自己的日期时间类型,这非常令人讨厌,这种类型在各种类型中都很常见数据库查询。
It's quite annoying that Python's default json encoder doesn't support its own datetime type, which is so common in all kinds of database queries.
我不想修改Python自己的json编码器。任何好的做法?非常感谢!
I don't want to modify Python's own json encoder. any good practice? Thanks a lot!
ps:我通过修改Python JSON编码器默认方法找到了一个肮脏的黑客:
ps: I found a dirty hack by modifying the Python JSON encoder default method:
更改:
def default(self, o):
raise TypeError(repr(o) + " is not JSON serializable")
收件人:
def default(self, o):
from datetime import date
from datetime import datetime
if isinstance(o, datetime):
return o.isoformat()
elif isinstance(o, date):
return o.isoformat()
else:
raise TypeError(repr(o) + " is not JSON serializable")
好吧,它只是开发环境的临时解决方案。
well, it will be a temporary solution just for dev environment.
但对于长期解决方案或生产环境,这非常难看,每次部署到新服务器时都必须进行修改。
But for long term solution or production environment, this is quite ugly, and I have to do the modification every time I deploy to a new server.
还有更好的方法吗?我不想修改Python代码本身,也不想修改Tornado源代码。我可以用自己的项目代码做些什么来实现这一目标吗?最好以一个步伐。
Is there a better way? I do not want to modify Python code itself, neither Tornado source code. Is there something I can do with my own project code to make this happen? preferably in one pace.
非常感谢!
推荐答案
< a href =http://docs.python.org/library/json.html#json.JSONEncoder.default>文档建议继承JSONEncoder并实现自己的默认方法。好像你基本上就在那里,而且这不是一个肮脏的黑客。
The docs suggest subclassing JSONEncoder and implementing your own default method. Seems like you're basically there, and it's not a "dirty hack".
默认编码器不处理原因日期是JSON中没有日期的标准表示。 有些人正在使用格式/日期(1198908717056)/
,但我个人更喜欢ISO格式。
The reason dates aren't handled by the default encoder is there is no standard representation of a date in JSON. Some people are using the format /Date(1198908717056)/
, but I prefer ISO format personally.
import datetime
class DateTimeEncoder(json.JSONEncoder):
def default(self, obj):
if isinstance(obj, datetime.datetime):
return obj.isoformat()
elif isinstance(obj, datetime.date):
return obj.isoformat()
elif isinstance(obj, datetime.timedelta):
return (datetime.datetime.min + obj).time().isoformat()
else:
return super(DateTimeEncoder, self).default(obj)
DateTimeEncoder().encode(object)
这篇关于Python JSON编码器支持datetime?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!