Home >Web Front-end >JS Tutorial >How to Resolve JavaScript's SyntaxError When Parsing Jinja-Rendered JSON Data?

How to Resolve JavaScript's SyntaxError When Parsing Jinja-Rendered JSON Data?

Susan Sarandon
Susan SarandonOriginal
2024-12-09 19:22:11699browse

How to Resolve JavaScript's SyntaxError When Parsing Jinja-Rendered JSON Data?

JavaScript Raises SyntaxError with Data Rendered in Jinja Template

When attempting to pass data as JSON from a Flask route to a Jinja template and iterate over it using JavaScript, one might encounter a "SyntaxError: Unexpected token '&'." This error arises when JSON.parse is called on the rendered data.

Issue

The issue stems from Flask's Jinja environment, which automatically escapes data rendered in HTML templates as a security measure. When attempting to use this escaped data as JSON in JavaScript, syntax errors occur.

Solution: Using tojson Filter

To resolve this issue, Flask provides the tojson filter. This filter automatically dumps the Python data to JSON and marks it safe for rendering in JavaScript.

Example:

return render_template("tree.html", tree=tree)
var tree = {{ tree|tojson }};

Alternative Solutions

Using safe Filter:

If not rendering JSON, the safe filter can be used to prevent Jinja from escaping the data.

Example:

var tree = {{ tree|safe }};

Using Markup:

The data can also be wrapped in Markup before rendering, which is equivalent to using the safe filter.

Example:

var tree = {{ tree }};

Passing Data to Jinja Instead of JavaScript

If the data is not intended for JavaScript usage but for Jinja, the tojson filter is not required. Pass the Python data directly and use it as any other data in the template.

Example:

return render_template("tree.html", tree=tree)
{% for item in tree %}
    <li>{{ item }}</li>
{% endfor %}

The above is the detailed content of How to Resolve JavaScript's SyntaxError When Parsing Jinja-Rendered JSON Data?. 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