小编use*_*612的帖子

row_to_json和psycopg2.fetchall()结果是列表中的列表,而不是列表中的字典

我使用Postgres的row_to_json()函数以json对象的形式检索数据,以便像使用python字典一样处理结果。

conn = psycopg2.connect("<My_DB_DSN>")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
query_sql = "SELECT row_to_json(row) FROM (SELECT id, name FROM products) row;" 
cur.execute(query_sql)
results = cur.fetchall()
print(results)
Run Code Online (Sandbox Code Playgroud)

结果是:

 [ [{"id": 1, "name": "Bob"}],
   [{"id": 2, "name": "Susan"}]
 ]
Run Code Online (Sandbox Code Playgroud)

我期待着这个结果:

 [ {"id": 1, "name": "Bob"},
   {"id": 2, "name": "Susan"}
 ]
Run Code Online (Sandbox Code Playgroud)

知道为什么我会得到第一个结果以及如何解决这个问题吗?

在postgres的命令行中运行SQL查询将按预期返回json:

{"id": 1, "name": "Bob"},
{"id": 2, "name": "Susan"}
Run Code Online (Sandbox Code Playgroud)

postgresql json psycopg2

0
推荐指数
1
解决办法
2339
查看次数

标签 统计

json ×1

postgresql ×1

psycopg2 ×1