2016-01-11 57 views
5

我想要使用Python中的pyobc庫檢索表的行。pyodbc返回的行不是JSON可序列化

我能夠成功檢索表中的表和字段。現在我有一個表命名爲「apx_roomtypes」有如下數據,

enter image description here

然而,當我的pyodbc行追加到一個列表,然後嘗試列表轉儲到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) 

如何解決這個問題?

回答

9

當您迭代rows時,每個row是實例,而不是list。如果你希望它返回鍵/值對,而不是值的列表的字典然後採取look at this answer

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

:您可以將其轉換爲一個列表(這是JSON序列化),如下所示。

+0

感謝您的鏈接兄弟,多數民衆贊成我需要 – Sajeetharan

+1

'列表(行)'應該做的伎倆沒有生成器表達式。 – kindall

+0

Thx @kindall - 已應用。 –