如何从数据库行动态构建 json?

How to dynamically build json from the database rows?

我想动态构建 json。一位客户的后端数据库 table 中的数据如下所示。 (下面的 '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": ""
        }

x 是一个 pyodbc.Row 对象。 字典键必须是可散列的。字符串、整数、元组等不可变对象实现哈希协议。

使用 xgrpnm 属性,如果它是原语,它应该是可哈希的。

results_ps = {}

for x in data:
    # ...
    results_ps[x.grpnm] = out