jsonify is not defined - Internal Server Error
Asked Answered
L

2

27

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

Lentigo answered 23/5, 2012 at 20:30 Comment(0)
K
76

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`
Kirovograd answered 23/5, 2012 at 20:39 Comment(3)
Fantastic, thanks! And yeah @ThiefMaster is correct - that's just whatever it ends up printing out eg: { "a": "Test1", "z": "Test2" }. Just started Python - wasn't aware that's how the docs were setup, that makes sense now. Is there a way to import a larger portion of the library? (Like in Java you can do import Java.util.*) Also - I just refreshed the page and I see Thiefmaster's new comment, but I didn't see the point someone else made.Lentigo
You could do from flask import * but I highly recommend against that since doing so can cause all kinds of difficult-to-debug namespace errors. If you have a long list of imports and want to split across several lines you can enclose in brackets/parens, e.g.: from flask import (fn1, fn2, fn3)Kirovograd
Good to know! I was mainly concerned with the clutter as I'm a code neat freak - so that works out perfect!Lentigo
M
1

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 *
Mertz answered 20/6, 2021 at 9:38 Comment(1)
Isn't the correct import (from flask import jsonify) already what the accepted answer is saying? And this comment underneath that answer also explains that import * is also an option but not recommended.C

© 2022 - 2024 — McMap. All rights reserved.