【问题标题】:row_to_json and psycopg2.fetchall() results are lists within a list instead of dictionaries in a listrow_to_json 和 psycopg2.fetchall() 结果是列表中的列表,而不是列表中的字典
【发布时间】:2018-12-25 03:38:19
【问题描述】:

我使用 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"}

【问题讨论】:

  • 更改查询以使用数组将所有行作为单个字符串返回? SELECT array(select row_to_json(row) FROM (SELECT id, product FROM products) 行);"

标签: python json postgresql psycopg2


【解决方案1】:

我想你想要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'}, ...]

【讨论】:

  • 非常感谢。完全符合我的要求。
  • 也谢谢,知道为什么 cursor_factory 不像许多类似的库/包那样默认执行它吗?
  • @Krystian Sztadhaus:Python 的 DB API 定义了一个 sequence of sequences
猜你喜欢
  • 1970-01-01
  • 2022-12-04
  • 1970-01-01
  • 2021-10-09
  • 2019-05-13
  • 1970-01-01
  • 2012-10-03
  • 2022-01-22
  • 1970-01-01
相关资源
最近更新 更多