Home > Web Front-end > JS Tutorial > Why Does JSON.parse Fail with a 'SyntaxError: Unexpected token '&'' When Rendering JSON Data from a Jinja Template?

Why Does JSON.parse Fail with a 'SyntaxError: Unexpected token '&'' When Rendering JSON Data from a Jinja Template?

DDD
Release: 2024-12-29 12:26:17
Original
1021 people have browsed it

Why Does JSON.parse Fail with a

JavaScript SyntaxError when Rendering JSON Data from Jinja Template

Issue Description

When attempting to iterate through JSON data rendered in a Jinja template using JavaScript, the browser throws a "SyntaxError: Unexpected token '&'" error. The issue arises when calling JSON.parse on the rendered data.

Solution

Flask's Template Escaping

Flask's Jinja environment applies automatic HTML escaping to data rendered in templates to mitigate security risks. However, this escaping can interfere with interpreting the data as JSON.

Flask provides the tojson filter to address this issue. It converts Python objects into JSON and marks them as safe for rendering.

return render_template('tree.html', tree=tree)
Copy after login
Copy after login

In the template:

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

Non-JSON Rendering

If the data is not intended for consumption by JavaScript, the tojson filter is unnecessary. Consider passing the Python data directly and utilizing it in the template as needed.

return render_template('tree.html', tree=tree)
Copy after login
Copy after login

In the template:

{% for item in tree %}
    <li>{{ item }}</li>
{% endfor %}
Copy after login

Disabling Escaping

If escaping is not needed and you already have JSON data as a string, you can disable escaping using the safe filter or Markup.

Using safe Filter:

return render_template('tree.html', tree=Markup(json.dumps(tree)))
Copy after login

In the template:

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

Using Markup:

return render_template('tree.html', tree=json.dumps(tree))
Copy after login

In the template:

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

The above is the detailed content of Why Does JSON.parse Fail with a 'SyntaxError: Unexpected token '&'' When Rendering JSON Data from a Jinja Template?. 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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template