Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

row_to_json and psycopg2.fetchall() results are lists within a list instead of dictionaries in a list

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"}
like image 855
user3515612 Avatar asked Jul 17 '18 12:07

user3515612


People also ask

What is Psycopg2 in Python?

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.

Is Psycopg2 asynchronous?

Psycopg allows asynchronous interaction with other database sessions using the facilities offered by PostgreSQL commands LISTEN and NOTIFY .

What is Psycopg cursor?

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.


1 Answers

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'}, ...]
like image 173
Maurice Meyer Avatar answered Oct 21 '22 05:10

Maurice Meyer