我想动态构建json。一位客户的后端数据库表中的数据如下所示。(下面的“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我尝试创建字典,但出现错误并且最终 JSON 响应没有运气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)因此,根据通过 api 传递的 custid,响应的预期 json 格式应为:"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条经验 获得超9个赞
x是一个pyodbc.Row对象。字典键必须是可散列的。字符串、int、元组等不可变对象实现了哈希协议。
使用如果它是原语应该是可散列的grpnm属性。x
results_ps = {}
for x in data:
# ...
results_ps[x.grpnm] = out
添加回答
举报
0/150
提交
取消