如果我使用 psycopg2,如何 return 字典或 json?

How to return dictonary or json if I use psycopg2?

我尝试使用 RealDictCursor:

cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cur.execute('SELECT * FROM items')
res = cur.fetchall()
print(res)
print(type(res[0]))

但是没用。结果:

[RealDictRow([('id', 1), ('name', 'apple')]), RealDictRow([('id', 2), ('name', 'pen')])]
<class 'psycopg2.extras.RealDictRow'>

我需要一个字典,输出如下:

[{"id": 1, "name": "apple"}, {"id": 2, "name": "pen"}]
<class 'dict'>

是的,我知道我可以用循环 for 来生成字典。但是我有 10000 行的 table,我需要快速显示 10000 个项目。 (我认为循环 for 解决我的问题不是很快。是真的吗?你能给我一个建议,以最少的速度很快解决我的问题时间)

如何获取?

PS: Flask 的 API 服务需要它,所以在此之后我需要像这样 return 它:

return jsonify({my_dictonary_sql_query})

您正在根据检索到的数据的打印人性化表示做出假设,在内部它是字典:

import json
#
return json.dumps(cur.fetchall())