I need to convert data from mySQL to JSON in Python using Flask.
I'm use the conversion directly in mySQL but it gives me error.
this is the code.
@app.route('/getdata')
def getdata():
cnx = mysql.connector.connect(**app.connDBConfig)
cursor = cnx.cursor()
query = "SELECT JSON_ARRAYAGG(JSON_OBJECT('nome', columnName, 'cognome', columnSur,)) from table;"
cursor.execute(query)
data = ""
for elem in cursor:
data = elem
return jsonify(data)
This give me a stange JSON
[
"[{"nome": "enry", "cognome": "ford"}, {"nome": "michel", "cognome": "rodriguez"}, {"nome": "paul", "cognome": "roger"}, {"nome": "marcial", "cognome": "corz"}]"
]
why this and how I can fix it?
EDIT
if I use fethall it always give me all the JSON in an only object
解决方案
You should be using cursor.fetchall() or cursor.fetchmany() to get the data from the cursor. Documentation here
The cursor object is NOT the data! , its just a handler that helps you get the data.