Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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})
like image 612
Vlad Avatar asked Jul 25 '19 20:07

Vlad


People also ask

Can JSON have a dictionary?

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.

Are dictionaries like JSON?

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.

What is commit in psycopg2?

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.


1 Answers

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())
like image 149
ipaleka Avatar answered Oct 14 '22 07:10

ipaleka