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})
JSON at its top-level is a dictionary of attribute/value pairs, or key/value pairs as we've talked about dictionaries in this class. The values are numbers, strings, other dictionaries, and lists.
A “JSON object” is very similar to a Python dictionary. A “JSON array” is very similar to a Python list. In the same way that JSON objects can be nested within arrays or arrays nested within objects, Python dictionaries can be nested within lists or lists nested within dictionaries.
commit()¶ Commit any pending transaction to the database. By default, Psycopg opens a transaction before executing the first command: if commit() is not called, the effect of any data manipulation will be lost.
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())
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