darkpool darkpool - 3 months ago 12
JSON Question

Unable to use dict sent from Django to template

I have the following dict in python which I send to the template:

mydict = {
"ABC": {
"target_weight": 1,
"target_ra_weight": 2
},
"XYZ": {
"target_weight": 3,
"target_ra_weight": 4
},
"JKL": {
"target_weight": 5,
"target_ra_weight": 6
}
}
return render(request, 'template.html', {'mydict': mydict})


I can't seem to assign this to a javascript variable and access the content. I have tried all of the following in the javascript section of my template:

var mydict = {{ mydict }};
> Uncaught SyntaxError: unexpected token {

var mydict = {{ mydict|safe }};
> Uncaught SyntaxError: unexpected token {

var mydict = {{ mydict|escapejs }};
> Uncaught SyntaxError: unexpected token {


The following allows me to create the variable, but when I try to access it (eg: console.log(mydict)), then I an error:

var mydict = JSON.parse('{{ mydict }}');
console.log(mydict);
> Uncaught SyntaxError: unexpected token { in JSON at position 1
// same thing happens when using |safe or |escapejs

Answer

You need JSON, not dict. Use json.dumps function:

import json

mydict = {
    "ABC": {
        "target_weight": 1,
        "target_ra_weight": 2
    },
    "XYZ": {
        "target_weight": 3,
        "target_ra_weight": 4
    },
    "JKL": {
        "target_weight": 5,
        "target_ra_weight": 6
    }
}
return render(request, 'template.html', {'mydict': json.dumps(mydict)})
Comments