Home >Web Front-end >JS Tutorial >Why Does My JavaScript Get a SyntaxError When Rendering JSON Data from a Jinja Template?
When passing JSON data from a Flask route to a Jinja template, the browser may throw a SyntaxError: Unexpected token '&'. Expected a property name when rendering the data. Understanding how to handle rendered JSON data in JavaScript is crucial for successful template handling.
Flask's Jinja environment automatically escapes data rendered in HTML templates to prevent security vulnerabilities. For data that needs to be treated as JSON, Flask provides the tojson filter, which dumps the data to JSON and marks it as safe. Using the tojson filter ensures that the data is rendered without escaping, allowing it to be parsed correctly in JavaScript.
tree = get_nodes("Root") return render_template("folder.html", data=tree|tojson)
var tree = {{ tree|tojson }};
Alternatively, in older Flask versions, the safe filter can be used to mark the data as safe:
var tree = {{ tree|tojson|safe }};
If the data has already been dumped to JSON, the safe filter can be used to mark it as safe for rendering without escaping:
return render_template('tree.html', tree=json.dumps(tree))
var tree = {{ tree|safe }};
Wrapping the JSON string in Markup is also equivalent to using the safe filter:
return render_template('tree.html', tree=Markup(json.dumps(tree)))
var tree = {{ tree }};
If the data is not being passed to JavaScript but used in Jinja, you can omit JSON rendering and use Python data directly:
return render_template('tree.html', tree=tree)
{% for item in tree %} <li>{{ item }}<li> {% endfor %}
The above is the detailed content of Why Does My JavaScript Get a SyntaxError When Rendering JSON Data from a Jinja Template?. For more information, please follow other related articles on the PHP Chinese website!