pyodbc返回的行不可JSON序列化 [英] Rows returned by pyodbc are not JSON serializable

查看:332
本文介绍了pyodbc返回的行不可JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Python中的pyobc库检索表的行.

I am trying to retrieve the rows of a table using pyobc library in Python.

我能够成功检索表的表和字段.现在,我有了一个名为"apx_roomtypes"的表,其数据如下,

I was able to retrieve the tables and fields of a table successfully. Now I have a table named "apx_roomtypes" with the data as follows,

但是,当我将pyodbc行附加到列表中,然后尝试将列表转储到JSON时,会收到错误消息

However, when I append the pyodbc rows to a list and then try dumping the list to JSON I get the error

TypeError:(1,标准",对于5个成员",123)不可JSON序列化

TypeError: (1, 'Standard', 'For 5 members', 123) is not JSON serializable

这是 python代码:

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上进行迭代时,每个row都是Row实例,而不是list.您可以将其转换为列表(可序列化JSON),如下所示:

When you are iterating over rows, each row is a Row instance and not a list. You can convert it to a list (which is JSON serializable) as follows:

rows = cursor.fetchall()
for row in rows:
    data.append([x for x in row]) # or simply data.append(list(row))

如果您希望它返回键/值对的字典而不是值列表,请查看此答案.

If you want it to return a dictionary of key/value pairs instead of a list of values then take a look at this answer.

这篇关于pyodbc返回的行不可JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆