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
DDDOriginal
2024-12-29 12:26:171009browse

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)

In the template:

var tree = {{ tree|tojson }};

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)

In the template:

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

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)))

In the template:

var tree = {{ tree }};

Using Markup:

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

In the template:

var tree = {{ tree|safe }};

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!

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