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
Release: 2024-12-26 12:19:10
Original
345 people have browsed it

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

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

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