Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

json.dumps return invalid json in flask view

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Why it happens?

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading