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
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
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.