使用 Flasks tojson 过滤器序列化日期时间
我收到此错误:
TypeError: datetime.datetime(2012, 2, 12, 0, 47, 6, 542000) is not JSON serializable
当 jinja 尝试解析此行时:
var root_node_info = eval({{ nd|tojson|safe }});
nd 包含来自我的 mongo 数据库的 bson 对象。其中一个字段是日期时间对象。我怎样才能让烧瓶正确序列化它?
这是我的 mongokit 模型(如果相关的话)
class Item(Document):
structure = {
"tldr": unicode,
"body": unicode,
"user": unicode,
"time_submitted": datetime.datetime,
"upvotes": int,
"downvotes": int,
"tags": [unicode]
}
validators = {
}
indexes = [
{'fields':['user']},
{'fields':['tags']}
]
use_dot_notation = True
required_fields = ['body', 'user', 'time_submitted']
default_values = {'time_submitted': datetime.datetime.utcnow}
def __repr__(self):
return '<item %r>' % (self._id)
I'm getting this error:
TypeError: datetime.datetime(2012, 2, 12, 0, 47, 6, 542000) is not JSON serializable
when jinja is trying to parse this line:
var root_node_info = eval({{ nd|tojson|safe }});
nd contains a bson object from my mongo database. One of the fields is a datetime object. How can I get flask to serialize this properly?
This is my mongokit model(in case its relevant)
class Item(Document):
structure = {
"tldr": unicode,
"body": unicode,
"user": unicode,
"time_submitted": datetime.datetime,
"upvotes": int,
"downvotes": int,
"tags": [unicode]
}
validators = {
}
indexes = [
{'fields':['user']},
{'fields':['tags']}
]
use_dot_notation = True
required_fields = ['body', 'user', 'time_submitted']
default_values = {'time_submitted': datetime.datetime.utcnow}
def __repr__(self):
return '<item %r>' % (self._id)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
JSON 不处理
datetime
对象。标准做法是将它们编码为 ISO 格式的字符串。这个关于 JSON 的问题提供了示例。您需要自己注册新的JSON编码器过滤器。JSON does not handle
datetime
objects. Standard practice is to encode them as strings in ISO format. This SO question about JSON provides examples. You will need to register the new JSON encoder filter yourself.只是需要注意的是。
从 v0.10 开始,Flask 能够指定您自己的
json_encoder
。Flask 的默认
JSONEncoder
是知道的日期(以及其他一些附加内容)。Just to be noted.
As of v0.10 Flask has the ability to specify your own
json_encoder
.And Flask’s default
JSONEncoder
is aware of dates (and few other additional things).