【发布时间】:2021-10-20 13:06:18
【问题描述】:
在我的烧瓶应用程序中,我尝试练习从 psql 表中获取数据并将其放入下拉列表中。我正在使用它来使用来自 here 的查询获取带有 psycopg2 的数据:
def load_authors(self):
# sql = "SELECT * FROM authors"
sql = "select array_to_json(array_agg(row_to_json(t))) from (select id, name from authors) t"
self.curs.execute(sql)
data = self.curs.fetchall()
print(data)
return data
这是我想要格式化为 json 的 psql 数据:
[(1, 'Christopher Paolini'), (2, 'Marie Lu'), (3, 'John Flanagan')]
前面的代码将数据导出到这个:
[([{'id': 1, 'name': 'Christopher Paolini'}, {'id': 2, 'name': 'Marie Lu'}, {'id': 3, 'name': 'John Flanagan'}],)]
它似乎采用了我想要的正确格式的 json:
[{'id': 1, 'name': 'Christopher Paolini'}, {'id': 2, 'name': 'Marie Lu'}, {'id': 3, 'name': 'John Flanagan'}]
然后把它放在另一个列表中?我对此还没有很深入的了解,所以我想知道它为什么会这样做以及如何解决它。我尝试了多个不同的查询,但到目前为止,它们都返回列表中的列表。
【问题讨论】: