Home >Backend Development >Python Tutorial >How to Resolve 'SyntaxError: Unexpected token '&'' When Parsing JSON in Jinja Templates?

How to Resolve 'SyntaxError: Unexpected token '&'' When Parsing JSON in Jinja Templates?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-20 10:13:16367browse

How to Resolve

Resolving JavaScript SyntaxError When Rendering JSON Data in Jinja Templates

When attempting to iterate over JSON data through JavaScript code rendered in a Jinja template, you may encounter a "SyntaxError: Unexpected token '&'" error when calling JSON.parse(). This error arises due to automatic escaping of data by Flask's Jinja environment when rendering in HTML templates.

Solution: Using the tojson Filter

To prevent this escape process and handle the data as JSON in JavaScript, Flask provides the tojson filter. It converts Python objects to JSON and marks them as safe for rendering in the template.

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

Handling Non-JSON Data

If you're not dealing with JSON data or have already converted it to a string, you can use the safe filter or wrap the string in Markup to prevent escaping:

return render_template("tree.html", tree=json.dumps(tree))
<script>
  var tree = {{ tree|safe }};
  // or
  var tree = {{ Markup(json.dumps(tree)) }};
</script>

Passing Raw Data

If you intend to use the data within the Jinja template itself rather than passing it to JavaScript, you can omit the tojson filter and use the raw Python data directly.

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

By implementing these techniques, you can effectively use rendered JSON data in JavaScript without encountering the SyntaxError issue.

The above is the detailed content of How to Resolve 'SyntaxError: Unexpected token '&'' When Parsing JSON in Jinja Templates?. 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