trivk96 trivk96 - 1 year ago 204
HTML Question

Pass JSON from flask to template and decode html entity

So I have been stuck on this for a while. I have a MongoDB that i query and return as JSON.

I do this by:


I then pass this into a flask template variable to use in an inline js script in HTML.

<div id="results">
<table id="results-table">


<script type="text/javascript" charset="utf-8">
dataset: {
records: {{results_json}}

The problem is that in the script, the JSON cannot be parsed by denotable properly because it contains
That is the entity value for a double quote but shouldn't it not appear like that if i inspect the source code. Shouldn't the html page display it as an
. This only happens in the script section. Not in the
tag (that prints out all

What am I misunderstanding?

Answer Source

To avoid XSS attacks, flask and other template languages escape values by default: it converts " into the HTML entity so that the browser reads it as text to be displayed for humans rather than the part of the HTML syntax (e.g. <a href="...">). This happens in all tags: inside the <p> tag you see the quote in your browser but the source code is still the entity.

To tell flask to not escape stuff, use {{results_json | safe}}. That's you asserting that the value is safe, not telling flask to make it safe (which is what it was doing before).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download