Home >Web Front-end >JS Tutorial >How to Safely Use JSON Data from Flask's Jinja Templates in JavaScript?

How to Safely Use JSON Data from Flask's Jinja Templates in JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-13 06:10:11914browse

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

  • safe Filter: Marks the data as safe for rendering without escaping.
  • Markup Wrapper: Wraps the string in Markup to achieve the same effect as the safe filter.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn