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
Asked
Active
Viewed 2,637 times
9

leonsas
- 4,718
- 6
- 43
- 70
-
is this question of any help to you? http://stackoverflow.com/q/1445989/92493 – Otto Allmendinger Jul 19 '12 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. – mouad Jul 19 '12 at 20:00
3 Answers
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 %}

kevin
- 198
- 1
- 6
12
Note that instead of using
{% autoescape off %}
{{ my_json }}
{% endautoescape %}
You can simply use a filter :
{{ my_json|safe }}

Byscripts
- 2,578
- 2
- 18
- 25
1
This works for me:
return HttpResponse(json.dumps({'foo' : 'bar'}, ensure_ascii=False),
mimetype='application/json')

Brandon Taylor
- 33,823
- 15
- 104
- 144
-
I use something like this when sending a simple HttpResponse, but in this case I had to render a template. – leonsas Jul 19 '12 at 20:17
-