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
Release: 2024-12-13 06:10:11
Original
913 people have browsed it

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)
Copy after login
Copy after login
<script>var tree = {{ tree|tojson }};</script>
Copy after login

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>
Copy after login

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)
Copy after login
Copy after login
{% for item in tree %}
    <li>{{ item }}</li>
{% endfor %}
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template