Skip to content
Advertisement

Django, how to convert Python dict to Javascript

In a Django app I have a dict created in a view and I want to use it in Javascript, but I get a syntax error

views.py

MY_TYPES = {
    'use_random': 0,
    'use_stages': 1,
    'use_import': 2,
    0: 'use_random',
    1: 'use_stages',
    2: 'use_import',
}


class Duo(View):
    url = 'duo/test_dict.html'

    def get(self, request, partner_pk):
        context = {
            'my_types': json.dumps(MY_TYPES),
        }
        return render(request, self.url, context)

test_dict.html

{% load static %}
<head>
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>
</head>`

{% block content %}
    <h1> Test dict</h1>

    <script>
        my_types = {{ my_types|safe }};
    </script>

    <script type="text/javascript" src="{% static 'js/test_dict.js' %}"></script>
{% endblock content %}

test_dict.js

$(document).ready(function () {
    console.log(my_types)
    console.log(JSON.parse(my_types))
});

Line 2 gives the output

{0: “use_random”, 1: “use_stages”, 2: “use_import”, use_random: 0, use_stages: 1, use_import: 2}

but throws the error in line 3

SyntaxError: Unexpected token o in JSON at position 1

What am I doing wrong?

Advertisement

Answer

but throws the error in line 3

SyntaxError: Unexpected token o in JSON at position 1

The reason this happens is because it is no longer a string but a JSON blob. You should pass this as a string if you want my_types to be a string:

<script>
my_types = '{{ my_types|safe }}';
</script>

by adding quotes ('…'), you thus wrap it in a string.

But this is actually not necessary, if you write my_types = {{ my_types|safe }};, then my_types will already be a JavaScript dictionary, and then calling JSON.parse(…) makes thus no sense.

Note that JSON does not allow integers to be keys, so Python will convert the integer keys to their string counterparts.

Advertisement