我在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)
问题是对象在对象内部。耶!
不是一个大问题,但我想知道是否有一个更优雅的解决方案。
答案 0 :(得分:1)
如果您转储整个结果集,那就会发生这种情况。使用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"}