我正在尝试使用 Python 中的 pyodbc 库检索表的行。
我能够成功检索表和表的字段。现在我有一个名为“apx_roomtypes”的表,其数据如下,
但是,当我将 pyodbc 行附加到列表,然后尝试将列表转储到 JSON 时,出现错误
TypeError: (1, 'Standard', 'For 5 Members', 123) 不可 JSON 序列化
这里是蟒蛇代码:
class execute_query:
def GET(self,r):
web.header('Access-Control-Allow-Origin', '*')
web.header('Access-Control-Allow-Credentials', 'true')
cnxn = pyodbc.connect(connection_string)
data = []
cursor = cnxn.cursor()
query = web.input().query
cursor.execute(query)
rows = cursor.fetchall()
for row in rows:
data.append(row)
return json.dumps(data)
我该如何修复这个错误?
当你迭代时rows
, each row
is a Row
实例而不是list
。您可以将其转换为列表(可 JSON 序列化),如下所示:
rows = cursor.fetchall()
for row in rows:
data.append([x for x in row]) # or simply data.append(list(row))
如果您希望它返回键/值对的字典而不是值列表,则采用看看这个答案 https://stackoverflow.com/a/16523148/276949.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)