Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 866
TJ Biddle Avatar asked May 23 '12 20:05

TJ Biddle


People also ask

What is Jsonify in Python?

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 .

Does Flask automatically Jsonify?

No, returning a dict in Flask will not apply jsonify automatically. In fact, Flask route cannot return dictionary.

What is the difference between Jsonify and json dumps?

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.


2 Answers

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`
like image 196
mechanical_meat Avatar answered Oct 12 '22 15:10

mechanical_meat


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 *
like image 1
Cyril Gupta Avatar answered Oct 12 '22 15:10

Cyril Gupta