I have a variable that contains JSON I need to pass into a template. I'm defining it as a variable and then passing it into the template successfully. However, I need the format to replace the quotes with ", but is replacing with '. This is causing issues with the service that I"m passing this to.
image_upload_params =
{
"auth": {
"key": "xxx"
},
"template_id": "xxx",
"redirect_url": "url-here",
}
Here is how it's coming up in the template:
{'redirect_url': 'url-here', 'template_id': 'xxx', 'auth': {'key': 'xxx'}}
Any idea how to get it to use " instead?
Django 2.1 added the json_script
template filter:
Safely outputs a Python object as JSON, wrapped in a tag, ready for use with JavaScript
Insert this in your template:
{{ value|json_script:"hello-data" }}
It renders to:
<script id="hello-data" type="application/json">{"hello": "world"}</script>
Then, you can safely load this object in a JavaScript variable:
var value = JSON.parse(document.getElementById('hello-data').textContent);
This approach is safer than simply writing var value = {{value|safe}};
because it protects you from XSS attacks (more in this ticket).
Use SafeString
:
from django.utils.safestring import SafeString
def view(request):
...
return render(request, 'template.html', {'upload_params': SafeString(json_string)})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With