Jsumner5 Jsumner5 - 5 months ago 47
Python Question

Parse json from mysql in flask to get a field from record

Mind that I am new to flask and python for that matter, I appreciate any help that anyone gives. I'm looking to access one of the fields of my JSON response(just the field not the entire response), how should I go about parsing the response. Image of the response attached below,thanks.



This is my main thread



from flask import Flask,render_template,request
from Qhandler import Qhandler
from MakePlayer import MakePlayer
app = Flask(__name__)

@app.route('/createplayer',methods=['GET','POST'] )
def showCreatePlayer():
if request.method == 'POST':
MakePlayer(request.form['playername'],request.form['playerteam'],request.form['playerrole'], request.form['playerpos'])
return "created player: <br>"+request.form['playername']+" "+request.form['playerteam']+" "+request.form['playerrole']+" "+request.form['playerpos']

return render_template("createPlayer.html")

@app.route('/sucess')
def success():
return "success"

@app.route('/showplayers')
def showPlayers():
Q = Qhandler()
return Q.displayQuery(""" select * from Player""")

if __name__ == '__main__':
app.run(debug=True)





This is my query handler



from flask import Flask, jsonify, json
from flaskext.mysql import MySQL

class Qhandler(object):
#global mysql
global cursor
global connection
global mysql
# database connection
app = Flask(__name__)

mysql = MySQL()
app.config['MYSQL_DATABASE_USER'] = 'root'
app.config['MYSQL_DATABASE_PASSWORD'] = 'root'
app.config['MYSQL_DATABASE_DB'] = 'Optimizer'
app.config['MYSQL_DATABASE_HOST'] = 'localhost'
mysql.init_app(app)



def ins(self,query):
try:
connection=mysql.connect()
cursor = connection.cursor()
cursor.execute(query)
connection.commit()

except:
print "error running query"

finally:
#cursor.close()
connection.close()

def displayQuery(self,query):
try:
connection = mysql.connect()
cursor = connection.cursor()
cursor.execute(query)
fetchedData = cursor.fetchall()
fetchedData = jsonify(fetchedData)
#fetchedData = json.dumps(fetchedData)
#record = json.loads(fetchedData)
#print "the resonse is here:"
return fetchedData

except:
print "error running query"

finally:
#cursor.close()
connection.close()


current response is



screenshot of results

Answer

Use "fetchedData = json.dumps(fetchedData)" instead of "fetchedData = jsonify(fetchedData)" then create a json decoder and parse the response, refer to below :

def displayQuery(self,query):
        try:
            connection = mysql.connect()
            cursor = connection.cursor()
            cursor.execute(query)
            fetchedData = cursor.fetchall()
            fetchedData = json.dumps(fetchedData)
            #create a json decoder
            d = json.JSONDecoder()
            fieldPlayerName = d.decode(fetchedData)
            #parse the json that is returned ( fieldPlayerName[0][1])
            print "should print the field with the player name",fieldPlayerName[0][1]
            return fieldPlayerName[0][1]