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
Release: 2024-12-20 10:13:16
Original
267 people have browsed it

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

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))
Copy after login
<script>
  var tree = {{ tree|safe }};
  // or
  var tree = {{ Markup(json.dumps(tree)) }};
</script>
Copy after login

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

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!

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