gpt4 book ai didi

python json dumps 将对象放入 row_to_json 返回的对象中

转载 作者:行者123 更新时间:2023-11-29 13:26:25 24 4
gpt4 key购买 nike

我在 python 中运行一个 Postgres 查询,它返回一个 JSON 对象数组。

    db = SQLDB('postgres://postgres:*****@localhost:5433/postgres', migrate=False)
q = ("SELECT row_to_json(t) FROM (SELECT * FROM fn_drivetime_eu_grid_" + request.get_vars.country + "_coord(" + request.get_vars.x + ", " + request.get_vars.y + ", " + request.get_vars.sec + ")) t;")
mySQL = db.executesql(q)
return json.dumps(mySQL)

问题是对象在对象内部。天哪!

问题不大,但我想知道是否有更优雅的解决方案。

enter image description here

最佳答案

如果您转储整个结果集,就会发生这种情况。使用 t 表:

create table t (a int, b text);
insert into t (a, b) values (1,'x'), (2,'y');

使用 Psycopg2:

query = "select row_to_json(t) from t"
cursor.execute(query)
rs = cursor.fetchall()

# dump the whole result set
print json.dumps(rs)
print

# dump each column:
for r in rs:
print json.dumps(r[0])
con.close()

输出:

[[{"a": 1, "b": "x"}], [{"a": 2, "b": "y"}]]

{"a": 1, "b": "x"}
{"a": 2, "b": "y"}

关于python json dumps 将对象放入 row_to_json 返回的对象中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33155830/

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