2015-10-15 68 views
0

我在python中運行Postgres查詢,它返回一個JSON對象數組。python json轉儲將對象放入row_to_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

+0

顯示的Python代碼和查詢輸出。 –

+0

我擴展了代碼示例。 –

+0

任何機會我們可以看到原始的JSON,而不是目前顯示的任何工具? –

回答

0

也就是說,如果你放棄整個結果集發生什麼。隨着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"}