Search code examples
pythonjsonpostgresqlpsycopg2execute

How to return dictonary or json if I use psycopg2?


I try to use RealDictCursor:

cur = conn.cursor(cursor_factory = psycopg2.extras.RealDictCursor)
cur.execute('SELECT * FROM items')
res = cur.fetchall()
print(res)
print(type(res[0]))

But it doesn't work. Result:

[RealDictRow([('id', 1), ('name', 'apple')]), RealDictRow([('id', 2), ('name', 'pen')])]
<class 'psycopg2.extras.RealDictRow'>

I need a dictonary, output like this:

[{"id": 1, "name": "apple"}, {"id": 2, "name": "pen"}]
<class 'dict'>

Yes, I know that I can to make dict with cycle for. But I have the table with 10000 rows and I need to show 10000 items fast. (I think that cycle for isn't very fast to solve my problem. Is it true? Can you give me a advice to solve my problem very fast with a minimum amount of time)

How can I get it?

PS: I need it for API service by Flask so after this I need to return it like this:

return jsonify({my_dictonary_sql_query})

Solution

  • You're making an assumption from the printed humanized representation of your retrieved data, internally it is the dictionary:

    import json
    #
    return json.dumps(cur.fetchall())