Joff
Joff

Reputation: 12197

cannot pass json in django context

I have some code like this.

def foobar():
    foo = [" 1", " 2", " 3"]
    context['json'] = json.dumps(foo)
    print context['json']
    return render_to_string('template', context)

I am getting what I think is correct printed to the terminal...

[" 1", " 2", " 3"]

but then in my javascript console I get the error (index):59 Uncaught SyntaxError: Unexpected token ;

and when I go to where it is I see this...

[\u0022 1\u0022, \u0022 2\u0022, \u0022 3\u0022]

So I can see it's turning to unicode somewhere and then not being converted back but IDK what to do about it.

In my template (in <script> tags) I am doing this:

var data = {
    labels: {{ labels|escapejs }}
    datasets: []
}

Upvotes: 3

Views: 233

Answers (1)

e4c5
e4c5

Reputation: 53774

Since you are trying to pass an a json representation of an array to your javascript through the django template, escapejs shouldn't be used! It should just be

labels: {{ labels }}

note that in your view you are using the variable name json while in your template you are using labels. I assume this is a typo

If you are having trouble with quotes,

{% autoescape off %}{{ labels }}{% endautoescape %}

Upvotes: 3

Related Questions