9

My view computes a json and outputs a json.dumps(), and I'm passing this as the dictionary key data. I'm trying to pass this to a script element in my template, but when rendering, the browser gets it as a python-escaped string{"nodes": [{"count":...... which isn't readable to the javascript. What I need is python to send it as a JS-escaped string, something like this {"nodes": [{"count":....... I tried str(data) and eval(data) without success. Basically I need python to send the string just as if it were printing it to the console. Thanks

2
  • is this question of any help to you? stackoverflow.com/q/1445989/92493 Commented Jul 19, 2012 at 19:57
  • I believe that if you're rendering it to your HTML template and that this HTML template will be send to the browser using the mime type 'text/html' (or it's variant) than the browser will escape the quotes and such, so i think it really depend on the mime type that you're sending to the browser. Commented Jul 19, 2012 at 20:00

3 Answers 3

15

If I understand well, you want to use a json in a template. In order to do that, you have to disable the escaping, for exemple like this.

{% autoescape off %}
var x={{json_var}}
{% endautoescape %}
Sign up to request clarification or add additional context in comments.

Comments

12

Note that instead of using

{% autoescape off %}
    {{ my_json }}
{% endautoescape %}

You can simply use a filter :

{{ my_json|safe }}

Comments

1

This works for me:

return HttpResponse(json.dumps({'foo' : 'bar'}, ensure_ascii=False),
    mimetype='application/json')

2 Comments

I use something like this when sending a simple HttpResponse, but in this case I had to render a template.
Np. Glad the answer was a simple one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.