Python datetime.datetime 不是 JSON 可序列化的
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/35869985/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
datetime.datetime is not JSON serializable
提问by Bruno Fernandes
I have a class in Python for retrieving all the columns in a table and return a JSON with this data.
我在 Python 中有一个类,用于检索表中的所有列并返回带有此数据的 JSON。
The problem is at least one of those columns is a datetime and I can't seem to understand how to serialize the columns so I can generate a valid JSON.
问题是这些列中至少有一个是日期时间,我似乎无法理解如何序列化这些列,以便生成有效的 JSON。
My class is as follows:
我的课如下:
class GetTodos(Resource):
def get(self):
con = cx_Oracle.connect('brunojs/[email protected]/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
Any hints on this?
这有什么提示吗?
回答by Michael Mulqueen
JSON doesn't have a default datetime type, so this is why Python can't handle it automatically. So you need to make the datetime into a string one way or another. I think the best way is to write a custom handler to help the json module.
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)
回答by feliperuhland
A simple way to do it is to cast your data to string. That way, you will be able to dump with json.
一种简单的方法是将数据转换为字符串。这样,您就可以使用 json 进行转储。
>>> datetime.now()
datetime.datetime(2016, 3, 8, 11, 37, 24, 123639)
>>> str(datetime.now())
'2016-03-08 11:37:27.511053'
But, you could also implement a serializer to transform the data as you want.
但是,您也可以实现一个序列化程序来根据需要转换数据。