我想動態(tài)構(gòu)建json。一位客戶的后端數(shù)據(jù)庫表中的數(shù)據(jù)如下所示。(下面的“grpnm”和“description”對于其他客戶可能不同)custid | grpnm | description | quantity | rate | amount1 | toys | abc | 100 | 5.5 | 5501 | toys | def | 10 | 4 | 401 | kitchen| abc | 5 | 3 | 151 | kitchen | def | 20 | 4.5 | 901 | bedroom | xyz | 10 | 5 | 50我嘗試創(chuàng)建字典,但出現(xiàn)錯誤并且最終 JSON 響應(yīng)沒有運氣custid = 1conn = pyodbc.connect(connection_string)cursor = conn.cursor()# get distinct grpnm for given customercursor.execute("select distinct grpnm from table where custid=?", custid)data = cursor.fetchall()for x in data: results_ps = {} out = [] cursor.execute("SELECT description,quantity,rate,amount FROM table where custid=? and grpnm=?", custid, x) columns = [column[0] for column in cursor.description] for row in cursor:# print(row) out.append(dict(zip(columns, row))) results_ps[x] = out # TypeError: unhashable type: 'pyodbc.Row' #print(out) print(results_ps)summary = json.dumps(results_ps, indent=4)print(summary)因此,根據(jù)通過 api 傳遞的 custid,響應(yīng)的預期 json 格式應(yīng)為:"summary": { "toys": [{ "description": "abc", "quantity": 100, "rate": 5.5, "amount": 550 }, { "description": "def", "quantity": 10, "rate": 4, "amount": 40 }], "kitchen": [{ "description": "abc", "quantity": 5, "rate": 3, "amount": 15 }, { "description": "def", "quantity": 20, "rate": 4.5, "amount": 90 } ], "bedroom": [{ "description": "xyz", "quantity": 10, "rate": 5, "amount": 50 }], "toysSubtotal": "", "kitchenSubtotal": "" , "bedroomSubtotal": "" }
1 回答

富國滬深
TA貢獻1790條經(jīng)驗 獲得超9個贊
x是一個pyodbc.Row對象。字典鍵必須是可散列的。字符串、int、元組等不可變對象實現(xiàn)了哈希協(xié)議。
使用如果它是原語應(yīng)該是可散列的grpnm屬性。x
results_ps = {}
for x in data:
# ...
results_ps[x.grpnm] = out
添加回答
舉報
0/150
提交
取消