Pass JSON to JS using Django render

Viewed 9695

In my views.py file, I have the following dictionary:

data = {'pk': '1980.24', 'model': 'artworks.metaData', 'fields': {'medium': 'Oil on canvas ', 'description': 'missing', 'credit': 'Gift of Nicholas Wyeth, 1980 ', 'collection': 2, 'height': '21.7', 'culture': 'Missing value', 'depictedPeople': 'missing', 'creation_date': '1896 ', 'account': 'n/a', 'original_url': 'http://www.metmuseum.org/art/collection/search/10738?sortBy=Relevance&what=Canvas%7cOil+paintings&ao=on&ft=*&offset=0&rpp=100&pos=1', 'url': 'annotatie01.io.tudelft.nl/collections/Metropolitan/1980.24.jpg', 'title': 'Gooseberries ', 'object_number': '1980.24', 'width': '35.7', 'artist': 'Joseph Decker '}}

I wish to be able to use/access this dictionary on my webpage.

My attempts:

I tried to send data using the render in my views.py,

def foo():
    context = {'data':data}
    return render(request, 'index.html', context=context)

to access it using:

<script type="text/javascript">
    var received_data  = "{{data}}";
</script>

Using this, data is transmitted, but it's garbled:

"{&#39;pk&#39;: &#39;1980.24&#39;, &#39;model&#39;: &#39;artworks.metaData&#39;, &#39;fields&#39;: {&#39;medium&#39;: &#39;Oil on canvas &#39;, &#39;descripti...etc

I tried using json.dumps(data) and JSON.parse(received_data ) but this raised an error:

 Uncaught SyntaxError: Unexpected token & in JSON at position 1.

In short:

How can I send JSON data from Py to JS using Django Render()?

3 Answers

You should pass the Django {{data}} to a raw JS String in order to prevent JS encoding/decoding problems.

<script type="text/javascript">
    let received_data  = String.raw`{{ data|safe }}`;
</script>
Related