我有一个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
Run Code Online (Sandbox Code Playgroud)
有什么暗示吗?
小智 28
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)
Run Code Online (Sandbox Code Playgroud)