Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON is appearing as unicode entities in Jinja2 template

I using Jinja2 with webapp2.

Jinja2 encodes all 'context' data into unicode as their doc says. This is proving problematic when I try to insert a json string into the the template:

jsonData = json.loads(get_the_file('catsJson.txt'))

I pass jsonData to template and I'm able to loop it successfully but when I insert a json element into HTML, it looks like this:

<option value='[u&#39;dogs&#39;, u&#39;cats&#39;]'>

I want it to look like this (as it is in the original json string):

<option value='["dogs", "cats"]'>

Any suggestions?

like image 498
userBG Avatar asked Jan 03 '12 10:01

userBG


1 Answers

In Jinja 2.9 I followed @Xion's advice to first convert the iterable elements to string using map('string'). The map filter result I then converted to a list which is finally output as JSON using the tojson built-in filter.

{{ jsonData|map('string')|list|tojson }} 
like image 158
M. F. Avatar answered Oct 01 '22 20:10

M. F.