使用Flask的tojson过滤器序列化日期时间

2 投票
2 回答
5409 浏览
提问于 2025-04-17 12:52

我遇到了这个错误:

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对象。其中一个字段是日期时间对象。我该如何让flask正确地处理这个呢?

这是我的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)

2 个回答

2

需要注意一下。

从版本0.10开始,Flask可以让你指定自己的 json_encoder

而Flask默认的 JSONEncoder 能够识别日期(还有一些其他的东西)。

5

JSON 不支持 datetime 对象。通常的做法是把它们转换成 ISO 格式的字符串。这个关于 JSON 的 问题提供了一些例子。你需要自己 注册 新的 JSON 编码器过滤器。

撰写回答