从postgres获取结果并在python中将其转换为json

从postgres获取结果并在python中将其转换为json,python,json,postgresql,api,postman,Python,Json,Postgresql,Api,Postman,当邮递员发出请求时,我必须从postgres db获取输出并作为JSON输出发送 我的代码是 import psycopg2 conn = psycopg2.connect(host="localhost", port="5000", dbname="stores", password="*****", user="postgres") cursor = conn.cursor() def c

当邮递员发出请求时,我必须从postgres db获取输出并作为JSON输出发送 我的代码是

import psycopg2

conn = psycopg2.connect(host="localhost", port="5000", dbname="stores", password="*****", user="postgres")
cursor = conn.cursor()

def check():
    db = conn.cursor()
    db.execute("select * from store1 as name;")
    dbop = db.fetchall()
    jop = dict(dbop)
    return jop


print(check())
我的数据库结构:

 name   | price

--------+-------

 chair  | 10.12
上述python代码的输出为:

{'chair': 10.12}
但我需要输出作为

{
"name" : "chair",
"price" : 10.12
}
根据fetchall获取查询结果的所有剩余行,并将它们作为元组列表返回

您可以自己进行映射,通过在源代码中显式命名列,从元组中创建字典列表,或者使用上述教程中的字典游标示例:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import psycopg2
import psycopg2.extras

con = psycopg2.connect(database='testdb', user='postgres',
                    password='s$cret')

with con:

    cursor = con.cursor(cursor_factory=psycopg2.extras.DictCursor) # <-- notice the factory
    cursor.execute("SELECT * FROM cars")

    rows = cursor.fetchall()

    for row in rows:
        print(f"{row['id']} {row['name']} {row['price']}")

我没有足够的关于dbop变量数据类型的信息,因此您可以这样使用:

导入psycopg2 conn=psycopg2.connecthost=localhost,port=5000,dbname=stores,password=****,user=postgres 光标=连接光标 def检查适配器查询结果: name=listqueryResult[0] 返回{ 姓名:姓名,, 价格:queryResult[名称] } def检查: db=连接光标 db.executeselect*from store1作为名称; dbop=db.fetchall jop=dictdbop 返回检查适配器 打印检查 编辑

正如Marek Piotrowskim所说,有更有效的解决方案,我强烈建议您实施它们

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import psycopg2
import psycopg2.extras

con = psycopg2.connect(database='testdb', user='postgres',
                    password='s$cret')

with con:

    cursor = con.cursor(cursor_factory=psycopg2.extras.DictCursor) # <-- notice the factory
    cursor.execute("SELECT * FROM cars")

    rows = cursor.fetchall()

    for row in rows:
        print(f"{row['id']} {row['name']} {row['price']}")