1

I am running a Postgres query in python which returns me an array of JSON objects.

    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)

The problem is that the objects are inside objects. Dawg!

Not a big problem, but I would like to know whether there is a more elegant solution for this.

enter image description here

Dennis Bauszus
  • 1,624
  • 2
  • 19
  • 44

1 Answers1

2

That is what happen if you dump the whole result set. With the t table:

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

Using 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()

Output:

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

{"a": 1, "b": "x"}
{"a": 2, "b": "y"}
Clodoaldo Neto
  • 118,695
  • 26
  • 233
  • 260