Home > Software engineering >  json.dumps return invalid json in flask view
json.dumps return invalid json in flask view

Time:11-26

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?

CodePudding user response:

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

CodePudding user response:

return render_template('index.html', data=json.dumps(products_list))

should be:

return render_template('index.html', data=json.loads(products_list))

json.loads takes a string and converts it into JSON object. json.dumps takes a JSON object and converts it into string.


>>> import json
>>> s = '[{"product_name": "product #1"}, {"product_name": "product #2"}]'
>>> json.dumps(s)
'"[{\\"product_name\\": \\"product #1\\"}, {\\"product_name\\": \\"product #2\\"}]"'
>>> json.loads(s)
[{'product_name': 'product #1'}, {'product_name': 'product #2'}]
>>> json.dumps(json.loads(s))
'[{"product_name": "product #1"}, {"product_name": "product #2"}]'

&#34; is the escape code for " character.

CodePudding user response:

Change your code like below code:

return render_template('index.html', data=json.dumps(products_list[0]))
  • Related