Javascript-readable json from python

My view computes json and outputs json.dumps() , and I pass this as the data dictionary key. I am trying to pass this to the script element in my template, but when rendering the browser receives it as a string with escaped python {"nodes": [{"count":...... that is not readable by javascript. I need python to send it as a string with escaped JS, something like this {"nodes": [{"count":...... I tried str(data) and eval(data) without success. Basically I need python to send the string the same way as if it were printing it to the console. Thanks

+8
json javascript python django
source share
3 answers

If I understand well, you want to use json in the template. To do this, you need to disable shielding, for example, like this.

 {% autoescape off %} var x={{json_var}} {% endautoescape %} 
+13
source share

Please note that instead of using

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

You can simply use the filter:

 {{ my_json|safe }} 
+11
source share

This works for me:

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

All Articles