Home >Backend Development >Python Tutorial >How to Avoid JavaScript SyntaxErrors When Using Jinja-Rendered JSON Data from Flask?

How to Avoid JavaScript SyntaxErrors When Using Jinja-Rendered JSON Data from Flask?

Barbara Streisand
Barbara StreisandOriginal
2024-12-26 12:19:10286browse

How to Avoid JavaScript SyntaxErrors When Using Jinja-Rendered JSON Data from Flask?

JavaScript SyntaxError with Jinja-Rendered Data

Problem:

When passing JSON data from Flask to a Jinja template that renders JavaScript, JSON.parse() fails with a SyntaxError.

Underlying Cause:

Flask escapes data rendered in HTML templates to prevent security vulnerabilities, affecting JSON data in JavaScript.

Solution:

Use the tojson Filter:

Flask's tojson filter converts Python objects to safe JSON and marks the data safe for rendering:

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

Alternative Options:

  • safe Filter or Markup Wrapping: If the data is already JSON, use the safe filter or wrap it in Markup.
return render_template("tree.html", tree=Markup(json.dumps(tree)))
var tree = {{ tree }};
  • Direct Python Data: If the data is not intended for JavaScript, use the Python data directly in the template without JSON conversion.
return render_template("tree.html", tree=tree)
{% for item in tree %}
    <li>{{ item }}<br /></li>
{% endfor %}

The above is the detailed content of How to Avoid JavaScript SyntaxErrors When Using Jinja-Rendered JSON Data from Flask?. 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