Search code examples
pythonjsonflaskinternal-server-error

jsonify is not defined - Internal Server Error


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...


Solution

  • 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`