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
Release: 2024-12-09 19:22:11
Original
698 people have browsed it

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

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

Using Markup:

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

Example:

var tree = {{ tree }};
Copy after login

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

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!

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