Home >Backend Development >Python Tutorial >How to Avoid JavaScript SyntaxErrors When Using Jinja-Rendered JSON Data from Flask?
Problem:
When passing JSON data from Flask to a Jinja template that renders JavaScript, JSON.parse() fails with a SyntaxError.
Underlying Cause:
Flask escapes data rendered in HTML templates to prevent security vulnerabilities, affecting JSON data in JavaScript.
Solution:
Use the tojson Filter:
Flask's tojson filter converts Python objects to safe JSON and marks the data safe for rendering:
return render_template("tree.html", tree=tree)
var tree = {{ tree|tojson }};
Alternative Options:
return render_template("tree.html", tree=Markup(json.dumps(tree)))
var tree = {{ tree }};
return render_template("tree.html", tree=tree)
{% for item in tree %} <li>{{ item }}<br /></li> {% endfor %}
The above is the detailed content of How to Avoid JavaScript SyntaxErrors When Using Jinja-Rendered JSON Data from Flask?. For more information, please follow other related articles on the PHP Chinese website!