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 ", #1" characters.
console.log([{"product_name": "product #1"}, {"product_name": "product #2"}]);
Why it happens?
CodePudding user response:
The problem here is that flask is escaping the quotes in your JSON by replacing them with "
. 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>
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"}]'
"
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]))