【问题标题】:How to dynamically build json from the database rows?如何从数据库行动态构建 json?
【发布时间】:2019-09-08 02:49:24
【问题描述】:

我想动态构建 json。一位客户的后端数据库表中的数据如下所示。 (对于其他客户,下面的“grpnm”和“描述”可能不同)

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": ""
        }

【问题讨论】:

    标签: python json pyodbc


    【解决方案1】:

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

    使用xgrpnm 属性,如果它是一个原语,它应该是可散列的。

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

    【讨论】:

    • 感谢@OluwafemiSule 的解释。 x.grpnm 工作,但现在我只得到响应中的最后一个列表(在我们的例子中是卧室列表)(而不是厨房和玩具列表)。我在代码中遗漏了什么吗?以及如何在“摘要”字典下获得完整的 json 响应。
    • 将字典的初始化移到循环外
    • 非常感谢@OluwafemiSule。循环外的dict初始化工作。进一步,我需要将其中一列的值(通过放入变量并在程序的其余部分中使用变量)从 cursor.execute 查询中的选定列中传递出来。
    • @more09 - 这是一个不同的问题。你应该ask a new question
    • @GordThompson ,肯定会发布一个新问题。由于涉及到相同的代码流,所以这里继续讨论。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-11
    • 2019-07-12
    • 2018-12-13
    • 2010-12-16
    • 2011-03-25
    • 2019-12-01
    相关资源
    最近更新 更多