Home >Web Front-end >JS Tutorial >How to Safely Use JSON Data from Flask's Jinja Templates in JavaScript?
How to Use JSON Data Rendered in Jinja Templates with JavaScript
In Flask, when passing data from a route to a Jinja template, automatic escaping is enabled to prevent security vulnerabilities. However, this can cause issues when attempting to use the data as JSON in JavaScript.
SyntaxError: Unexpected Token '&'
When trying to use the rendered data with JSON.parse, the error "SyntaxError: Unexpected token '&'" occurs because Jinja escapes the "&" character in the output.
Using tojson Filter
To resolve this, Flask provides the tojson filter which safely dumps the data as JSON and marks it as safe for rendering:
return render_template('tree.html', tree=tree)
<script>var tree = {{ tree|tojson }};</script>
Previous Flask Behavior and safe Filter
Older versions of Flask did not mark the dumped data as safe, so the following approach was used:
<script>var tree = {{ tree|tojson|safe }};</script>
However, this is no longer necessary.
Alternative Approach Without JSON
If you're not passing the data to JavaScript but using it in Jinja, you can pass the original Python data without calling tojson:
return render_template('tree.html', tree=tree)
{% for item in tree %} <li>{{ item }}</li> {% endfor %}
Other Options
The above is the detailed content of How to Safely Use JSON Data from Flask's Jinja Templates in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!