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.
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>
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>
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!