Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the difference between jsonify and tojson in Flask?

I want to use some data from my Flask view in a JavaScript block in my template. I tried using jsonify and tojson, but that gave an error. What is the difference between the two? How do I pass JSON to JavaScript in a template?

@app.route('/stocks')
def stocks():
    stocks = jsonify({"aapl":{"price":700, "volume":5000000}, "goog":{"price":655, "volume":9750000}})
    return render_template("stocks.html", stocks=stocks)
<script>var zipcodes = {{ stocks|tojson }};</script>
TypeError: <Response 21 bytes [200 OK]> is not JSON serializable
like image 494
Michael Jones Avatar asked Dec 03 '15 22:12

Michael Jones


People also ask

What does Jsonify do in Flask?

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.

Do you need Jsonify in Flask?

In the conditional, Flask checks if the body is of type dict and if so calls jsonify . To see this in action refer to the previously mentioned line in the core Flask app.py . So, while we no longer need to explicitly call jsonify it is still very much being used by the application itself.

How do I return data in JSON format in Flask?

There are two methods you can use to return JSON data in your Flask application's view: by returning a Python dictionary, or by using Flask's jsonify() method.

Does JSON dumps return a string?

dumps() takes in a json object and returns a string.


1 Answers

jsonify returns a Response object to be returned from the Flask view as a JSON response to the client so in this case stocks is not a JSON object but a Response object.

If you want to use JSON but not directly return it to the client by using, you can use the tojson filter to convert an object to JSON in the template.

When you need to have JSON in your template, such as to use it in a JavaScript variable, you should use tojson. When you need to return a JSON response to the client you should use jsonify.

like image 82
mehdy Avatar answered Sep 21 '22 06:09

mehdy