我想动态构建json。一位客户的后端数据库表中的数据如下所示。(下面的“grpnm”和“description”对于其他客户可能不同)
custid | grpnm | description | quantity | rate | amount
1 | toys | abc | 100 | 5.5 | 550
1 | toys | def | 10 | 4 | 40
1 | kitchen| abc | 5 | 3 | 15
1 | kitchen | def | 20 | 4.5 | 90
1 | bedroom | xyz | 10 | 5 | 50
我尝试创建字典,但出现错误并且最终 JSON 响应没有运气
custid = 1
conn = pyodbc.connect(connection_string)
cursor = conn.cursor()
# get distinct grpnm for given customer
cursor.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": ""
}
富国沪深
相关分类