1

i'm developing Flask App. I want to transfer simple json from the app.py to the html page.

This is the relevant code at app.py:

jsonArr = [{"type": "circle", "label": "New York"},
           {"type": "circle", "label": "New York"}]

return render_template('demo.html', foo=42, imgs=jsonArr)

This is how I receive it it javascript script inside the html:

    <script>
    console.log("HI")
    var foo = {{ foo }}
    console.log(foo)
    var images = {{ imgs }}
    console.log(images)

foo is received correctly (I see the printing on the console when I remove the lines for receiving imgs)

But imgs makes error: Uncaught SyntaxError: Unexpected token & This is what I see in the chrome browser sources:

var images = [[&#39;circle&#39;, &#39;New York&#39;], [&#39;triangle&#39;, &#39;Amsterdam&#39;]]

This is the html declerations:

<!DOCTYPE html>
<html class="no-js" lang="en">

I've tried adding/removing <meta charset="UTF-8"> but it didn't work.

What am I missing? Thanks

jonb
  • 845
  • 1
  • 13
  • 36

2 Answers2

1

In order to avoid cross-site-scripting attacks, flask automatically escapes HTML sequences. If you want to avoid this, you can directly tell Flask you know what you're doing:

https://stackoverflow.com/a/3266740/3029173

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

However!! This is risky from a security perspective. If you have any user data that can end up in the JSON, you need to consider another approach.

You would need to sanitize the JSON so a user doesn't come along with a string of </script><script>do bad things here</script>

AnilRedshift
  • 7,937
  • 7
  • 35
  • 59
1

You should have a separate route with the data in JSON format.

from flask import jsonify

jsonArr = [{"type": "circle", "label": "New York"},
       {"type": "circle", "label": "New York"}]

return jsonify(jsonArr)
tomasantunes
  • 814
  • 2
  • 11
  • 23