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

JavaScript

test_dict.html

JavaScript

test_dict.js

JavaScript

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:

JavaScript

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