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
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.
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.
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.
dumps() takes in a json object and returns a string.
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
.
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