【问题标题】:datetime.datetime is not JSON serializable [duplicate]datetime.datetime 不是 JSON 可序列化的 [重复]
【发布时间】:2016-06-22 13:15:31
【问题描述】:

我在 Python 中有一个类,用于检索表中的所有列并返回包含此数据的 JSON。

问题是这些列中至少有一个是日期时间,我似乎无法理解如何序列化这些列,以便生成有效的 JSON。

我的班级如下:

class GetTodos(Resource):
    def get(self):
        con = cx_Oracle.connect('brunojs/bdpf5@127.0.0.1/orcl')
        cur = con.cursor()
        cur.execute("select * from organite_repository")
        r = [dict((cur.description[i][0], value) \
                for i, value in enumerate(row)) for row in cur.fetchall()]
        cur.connection.close()
        return (r[0] if r else None) if None else r 

对此有何提示?

【问题讨论】:

    标签: python datetime


    【解决方案1】:

    一种简单的方法是将数据转换为字符串。 这样,您就可以使用 json 进行转储。

    >>> datetime.now()
    datetime.datetime(2016, 3, 8, 11, 37, 24, 123639)
    
    >>> str(datetime.now())
    '2016-03-08 11:37:27.511053'
    

    但是,您也可以实现一个序列化程序来根据需要转换数据。

    【讨论】:

    • 应该像 str(datetime.datetime.now()),因为:[ERROR] AttributeError: module 'datetime' has no attribute 'now'
    【解决方案2】:

    JSON 没有默认的日期时间类型,所以这就是 Python 不能自动处理它的原因。因此,您需要以一种或另一种方式将日期时间转换为字符串。我认为最好的方法是编写一个自定义处理程序来帮助 json 模块。

    import datetime
    import json
    
    def datetime_handler(x):
        if isinstance(x, datetime.datetime):
            return x.isoformat()
        raise TypeError("Unknown type")
    
    json.dumps(data, default=datetime_handler)
    

    【讨论】:

    • 我用raise x 更新了我的情况。
    • 使用json.JSONEncoder.default = datetime_handler自动解析日期时间,而不是每次都使用default=datetime_handler
    • 我收到了一个 TypeError 这个答案,它说 datetime_handler 接受 1 个参数,但 JSON 正在尝试处理 2 个。
    • 刚刚使用 Python 2.6.9 和 3.4.1 尝试了我的原始答案,并且两者都适用。如果您遵循@ChaimG 的答案,您可能还需要指定一个 self 参数,因为您已经覆盖了它:docs.python.org/3/library/json.html#json.JSONEncoder.default
    • 也许更新 json 模块并允许日期时间转换是明智的?
    猜你喜欢
    • 2017-10-24
    • 2018-11-18
    • 2015-09-21
    • 2014-04-12
    • 2014-10-28
    • 2016-12-20
    • 2019-06-01
    • 1970-01-01
    相关资源
    最近更新 更多