gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 14:06:15 25 4
gpt4 key购买 nike

我使用 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)

这导致:

 [ [{"id": 1, "name": "Bob"}],
[{"id": 2, "name": "Susan"}]
]

我期待这样的结果:

 [ {"id": 1, "name": "Bob"},
{"id": 2, "name": "Susan"}
]

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

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

{"id": 1, "name": "Bob"},
{"id": 2, "name": "Susan"}

最佳答案

我认为您需要 RealDictCursor,它会将每一行作为字典返回,您不需要修改 SQL 查询:

from psycopg2.extras import RealDictCursor

cur = conn.cursor(cursor_factory=RealDictCursor)
query_sql = "SELECT id, name FROM products where id < 10"
cur.execute(query_sql)
results = cur.fetchall()
print(results)

返回:

[{'id': 2L, 'name': 'Foo'}, {'id': 4L, 'name': 'Bar'}, ...]

关于python - row_to_json 和 psycopg2.fetchall() 结果是列表中的列表而不是列表中的字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51381312/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com