Render JSON without replacing characters in Jinja
Jinja autoescapes potentially unsafe characters (such as quotes) to avoid security issues. You need to tell it that the data you are rendering is safe, either by using the |safe
filter in the template or wrapping it in Markup
in the view. You can also use the |tojson
filter rather than parsing and marking the JSON manually.
Use Markup
to mark it safe from the view.
from markupsafe import Markup
render_template('index.html', piedata=Markup(json.dumps(pieData)))
Or mark it safe in the template.
{{ piedata|safe }}
Preferably, just convert it in the template without calling json.dumps
in the view. Older versions of Flask required calling |tojson|safe
, but the |safe
is no longer needed.
{{ piedata|tojson }}
Comments
-
Fizi almost 2 years
I have some Python data that will be sent to a JavaScript chart. I dump it to JSON and pass it to the template. When I render the data, it contains html entities (
"
) instead of quotes, which isn't valid. How do I correctly pass the JSON data from Python to JavaScript?pieData = [{'color': '#400068', 'name': 'xyz', 'value': 10}, {'color': '#4a8624', 'name': 'abc', 'value': 30}] render_template('index.html', piedata=json.dumps(pieData))
var pieData2 = {{ piedata }}; // renders as var pieData2 = [{"color": "#5461ae", "name": "fizi.yadav", "value": 10}, {"color": "#e1dce4", "name": "surya.pradhan", "value": 30}, {"color": "#7835f0", "name": "fred.hsu", "value": 276}]