Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using JSON in django template

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?

like image 610
Brenden Avatar asked Jun 08 '11 22:06

Brenden


2 Answers

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).

like image 71
Benoit Blanchon Avatar answered Oct 09 '22 09:10

Benoit Blanchon


Use SafeString:

from django.utils.safestring import SafeString

def view(request):
    ...
    return render(request, 'template.html', {'upload_params': SafeString(json_string)})
like image 24
zeekay Avatar answered Oct 09 '22 09:10

zeekay