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

Vla*_*lad 5 python postgresql json psycopg2 execute

我尝试使用 RealDictCursor:

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

但它不起作用。结果:

[RealDictRow([('id', 1), ('name', 'apple')]), RealDictRow([('id', 2), ('name', 'pen')])]
<class 'psycopg2.extras.RealDictRow'>
Run Code Online (Sandbox Code Playgroud)

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

[{"id": 1, "name": "apple"}, {"id": 2, "name": "pen"}]
<class 'dict'>
Run Code Online (Sandbox Code Playgroud)

是的,我知道我可以用循环来制作 dict for . 但是我的表有 10000 行,我需要快速显示 10000 个项目。(我认为周期不是很快解决我的问题。是真的吗?你能给我一个建议,用最短的时间量非常快的解决我的问题

我怎么才能得到它?

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

return jsonify({my_dictonary_sql_query})
Run Code Online (Sandbox Code Playgroud)

ipa*_*eka 6

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

import json
#
return json.dumps(cur.fetchall())
Run Code Online (Sandbox Code Playgroud)

  • 完全清楚的是,根据[文档](http://initd.org/psycopg/docs/extras.html#real-dictionary-cursor),“RealDictRow”是“dict”的子类。 (3认同)
  • 此外,并非 Postgres 返回的所有字段都可以使用 json.dumps 进行简单序列化。以日期时间字段为例。您可以默认使用 json.dumps(cur.fetchall(), default=str) 字符串化这些编码器,也可以添加您自己的编码器(请参阅:https://docs.python.org/3/library/json.html#json)。 JSON编码器) (2认同)