0

I have the following situation and I don't have any solution

I have the following view.py

def getData(request, ft):
context = {'hello': 'World',
        'ABC': 123,
        456: 'abc'}

    dataJSON = dumps(context)
    return HttpResponse(request, 'lic_usage_overview.html', {"data": dataJSON})

Now I need to assign these values to a array Object in javascript/jQuery. I tried in this way (and another 100 ways) but is not working:

<script>
var data = JSON.parse({{data|escapejs}});
for(var x in data){
    console.log(x+' : '+data[x]);
}
</script>

The console give me this as result:

VM574 jquery-3.5.1.min.js:2 Uncaught SyntaxError: Unexpected token u in JSON at position 0
    at JSON.parse (<anonymous>)

Have anybody any idea about how to solve this problem?

Thanks

zgrizzly_7
  • 773
  • 2
  • 10
  • 22
  • Did you check [this](https://stackoverflow.com/a/739974/10606400) answer ? – Swati Oct 02 '20 at 14:04
  • yes I checked this answer and a lot similar like this one but I still have the problem because {{data|escapejs}} or {{data|safe}} is identity as error – zgrizzly_7 Oct 04 '20 at 14:55
  • Why not use ajax simply ? – Swati Oct 04 '20 at 16:19
  • would you be so kind to let me a simple example for this – zgrizzly_7 Oct 04 '20 at 17:32
  • Hi , i have limited knowledge in django .. but with your current updated code code i can see you are returning json from backend ..`{"data": dataJSON}` so why not called that page using ajax and get the return data i.e :`{"data": dataJSON}` . – Swati Oct 05 '20 at 03:44

1 Answers1

0

I don't think that you should be able to use list comprehension that way. Try defining this in the view and pass it as a parameter to the template.

Zhivko Zaikov
  • 409
  • 4
  • 10