I have a bunch of unicode strings in my data which I need to pass from my django view to template for using in a JavaScript scriptlet that passes it to the web back and forth.
The problem is I want the strings to be represented in the JavaScript unicode form but I get strings with a u prefix from python.
For example, for the string mężczyźni, Python stores it as u’m\u0119\u017cczy\u017ani’ but when it is passed to the template, it does not remove the u prefix which creates problems for JavaScript while processing it. I want it to be simply ‘m\u0119\u017cczy\u017ani’ so that the JavaScript code in the template can use it.
I tried using urqluote, smart_unicode, force_unicode but couldn’t hit a solution or even a hack.
What do I do ?
Edit: Django 1.7+ no longer includes simplejson. Instead of
write
and then use
jsoninstead ofsimplejson.You are probably printing the python repr of your data dict, and trying to parse it in javascript:
Instead, you could export your data in json:
And load the data directly in javascript:
You could also make a template filter:
And in your template:
Note that you should be careful with XSS, if some of “data” comes from user input, then you should sanitize it.