从JSON中提取key:value、key2:value2字符串

2w2cym1i  于 2023-11-20  发布在  其他
关注(0)|答案(1)|浏览(181)

当我使用Sanic的代码时,

@app.route('/orders', methods=["GET", "OPTIONS"])
async def get_orders(request):
    conn = psycopg2.connect(user='postgres', password='baldauren15', database='pyDB', host='127.0.0.1', port=5432)
    cursor = conn.cursor()
    if request.method == "GET":
        cursor.execute('SELECT * from orders_view')
        record = cursor.fetchall()
        ecdj = json.dumps(record, default=str)
        return response.html(ecdj)
    else:
        return response.json({"status": "not found"})

字符串
在输出中,我们有:

[[7, "baby", "Americano", "Not ready", "2023-01-08 07:05:06"], [5, "nurtyleu", "Capucino", "Ready", "2023-01-08 07:05:06"]]


我的问题是我怎么能这样做:

id:7, name:baby, order:Americano, status:Not ready, time:2023-01-08 07:05:06


下一个订单

id:5, name:Nurtyleu, order:Americano, status:Not ready, time:2023-01-08 07:05:06


我想要没有括号的.
我尝试将JSON更改为HTML或文本,我使用class orders(object):而不是数组orders=[],但我总是得到带有括号或JSON的输出。

eivgtgni

eivgtgni1#

如果你想要一个字典列表,你需要从cursor.description中读取结果列名,然后用它形成records

cursor.execute('SELECT * from orders_view')
columns = [desc[0] for desc in cursor.description]
records = [dict(zip(columns, row)) for row in cursor.fetchall()]
return response.html(json.dumps(records, default=str))

字符串

相关问题