Playing around with Flask and just wanted to print out some data as JSON formatted, but I keep getting the error:
NameError: global name 'jsonify' is not defined
from flask import Flask
from flask import json
app = Flask(__name__)
@app.route("/")
def testJSON():
x = "Test1"
y = "Test2"
return jsonify(a=x,z=y)
if __name__ == "__main__":
app.debug = True
app.run()
Their documentation says that I either need Python 2.6 or simplejson to be installed - I have both.
Python 2.7.3:
sys.version '2.7.3 (default, May 9 2012, 23:42:16) \n[GCC 4.4.3]'
simplejson:
root@Python:~/PythonScripts# pip install simplejson Requirement already satisfied (use --upgrade to upgrade): simplejson in /usr/local/lib/python2.7/site-packages Cleaning up...
jsonify is a function in Flask's flask. json module. jsonify serializes data to JavaScript Object Notation (JSON) format, wraps it in a Response object with the application/json mimetype. Note that jsonify is sometimes imported directly from the flask module instead of from flask. json .
No, returning a dict in Flask will not apply jsonify automatically. In fact, Flask route cannot return dictionary.
jsonify() is a helper method provided by Flask to properly return JSON data. jsonify() returns a Response object with the application/json mimetype set, whereas json. dumps() simply returns a string of JSON data. This could lead to unintended results.
jsonify()
is a function contained within the flask
module.
So you would need to import it.
Change the beginning of your script to:
from flask import jsonify # <- `jsonify` instead of `json`
It seems that Jsonify function was earlier included by default when flask was imported, but now when you write
import flask
It does not import jsonify too. All you need to do is import jsonify explicitly
Use this.
import flask
from flask import jsonify
That will enable the jsonify function for you
Now, you might be using other things from flask and this can happen over and over for different things, so you might want to do this instead which will import jsonify and all the other components of flask in one go.
import flask
from flask import *
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