Home >Web Front-end >JS Tutorial >Why Does JSON.parse Fail with a 'SyntaxError: Unexpected token '&'' When Rendering JSON Data from a Jinja Template?
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.
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 }};
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 %}
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!