1

I have a simple code:

products_list: list = [{"product_name": "product #1"}, {"product_name": "product #2"}]
return render_template('index.html', data=json.dumps(products_list))

My index template:

<body>
    <script>
        console.log({{ data }});
    </script>
</body>

But on the page i get an invalid json with &#34, #1&#34 characters.

 console.log([{&#34;product_name&#34;: &#34;product #1&#34;}, {&#34;product_name&#34;: &#34;product #2&#34;}]);

Why it happens?

wesose1216
  • 13
  • 2
  • Why are you using a template for code? Code is already code; can’t you just pass the object as a function parameter or something? The template rendering engine assumes templates are HTML, which is why it’s turning the quotation marks in your JSON into HTML entities. – Mark Reed Nov 26 '21 at 13:33

1 Answers1

0

The problem here is that flask is escaping the quotes in your JSON by replacing them with &#34;. You can disable this by adding the |safe filter to your template.

So your HTML will be:

<body>
    <script>
        console.log({{ data|safe }});
    </script>
</body>

Related Question

TheNightHawk
  • 505
  • 2
  • 7