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

3
  • Show the Python code and the query output. Commented Oct 15, 2015 at 18:30
  • I extended the code sample. Commented Oct 16, 2015 at 10:15
  • Any chance we can see the raw JSON instead of whatever tool it's currently showing in? Commented Oct 16, 2015 at 10:27

1 Answer 1

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"}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.