【问题标题】:In (python3) psycopg2 return results as string rather than dict在 (python3) psycopg2 中,将结果返回为字符串而不是 dict
【发布时间】:2019-03-10 21:41:10
【问题描述】:

在 psycopg2 中,有没有办法让光标以字符串而不是 JSON(或字符串)格式而不是字典对象的形式返回结果?

示例

# connect to database 
conn = psycopg2.connect(host=host, port=port, user=usr, password=passwd, dbname=dbn) 
cur = conn.cursor(cursor_factory=RealDictCursor)
# CREATE table and INSERT 
cur.execute("CREATE TABLE t1(c char, i int);")
cur.execute("INSERT INTO t1(c, i) VALUES ('a', 1), ('b', 2), ('c', 3)"); 
# Execute query 
cur.execute("SELECT COUNT(*) FROM t1;") 
output1 = cur.fetchall() 
cur.execute("SELECT * FROM t1;")
output2 = cur.fetchall()

Expect - 格式化为 JSON 或字符串的对象列表

output1 - ['{"count": 3}']
output2 - ['{"c": "a", "i": 1}', '{"c": "b", "i": 2}', '{"c": "c", "i": 3}']

实际 - 字典对象列表

output1 - [{'count': 3}]
output2 - [{'c': 'a', 'i': 1}, {'c': 'b', 'i': 2}, {'c': 'c', 'i': 3}]

我目前正在使用 JSON 模块将每个对象转换为 JSON,但我想知道是否有更简单的方法(即在 psycopg2 中)。

【问题讨论】:

  • output1 = json.dumps(cur.fetchall()) 还不够简单?
  • @klin,我举了一个简单的例子,但实际情况包含 datetime.datetime 对象,因此如果我使用你的方法,我会出错。这意味着为了使用 json 函数,我必须更新列表,然后转换 JSON...

标签: python-3.x postgresql psycopg2


【解决方案1】:

您当前在应用程序中呈现视图的方式是正确的,您应该继续这样做。

原则上,有一种方法可以在 PostgreSQL 中将您的视图呈现为 JSON,但这样做没有任何意义,因为呈现您的视图是您从数据库在您的架构。

【讨论】:

  • 顺便说一下@OShadmon,我想赞扬你采纳架构建议。从不同和相互冲突的角度看待自己的心理结构的能力是男人与男孩和女人与女孩的区别。
猜你喜欢
  • 1970-01-01
  • 2023-03-13
  • 1970-01-01
  • 2014-06-19
  • 1970-01-01
  • 2017-08-25
  • 1970-01-01
  • 2020-10-15
  • 2019-09-15
相关资源
最近更新 更多