I use Postgres' row_to_json() function to retrieve data as json objects in order to work with the result like with a python dictionary.
conn = psycopg2.connect("<My_DB_DSN>")
cur = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)
query_sql = "SELECT row_to_json(row) FROM (SELECT id, name FROM products) row;"
cur.execute(query_sql)
results = cur.fetchall()
print(results)
This results to:
[ [{"id": 1, "name": "Bob"}],
[{"id": 2, "name": "Susan"}]
]
I was expecting this result:
[ {"id": 1, "name": "Bob"},
{"id": 2, "name": "Susan"}
]
Any idea why I get the first result and how can I fix this?
Running the SQL query in postgres' command line will return the json as expected:
{"id": 1, "name": "Bob"},
{"id": 2, "name": "Susan"}
Psycopg2 is a PostgreSQL database driver, it is used to perform operations on PostgreSQL using python, it is designed for multi-threaded applications. SQL queries are executed with psycopg2 with the help of the execute() method. It is used to Execute a database operation query or command.
Psycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY .
The Cursor class of the psycopg library provide methods to execute the PostgreSQL commands in the database using python code. Using the methods of it you can execute SQL statements, fetch data from the result sets, call procedures. You can create Cursor object using the cursor() method of the Connection object/class.
I think you want RealDictCursor
, this returns each row as dict and you dont need to modify your SQL queries:
from psycopg2.extras import RealDictCursor
cur = conn.cursor(cursor_factory=RealDictCursor)
query_sql = "SELECT id, name FROM products where id < 10"
cur.execute(query_sql)
results = cur.fetchall()
print(results)
Returns:
[{'id': 2L, 'name': 'Foo'}, {'id': 4L, 'name': 'Bar'}, ...]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With