JSON在Jinja2模板中显示为Unicode实体 [英] JSON is appearing as unicode entities in Jinja2 template

查看:397
本文介绍了JSON在Jinja2模板中显示为Unicode实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Webapp2中使用Jinja2.

I using Jinja2 with webapp2.

Jinja2如其文档所述将所有上下文"数据编码为unicode.当我尝试将json字符串插入模板时,这被证明是有问题的:

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'))

我将jsonData传递给模板,并且能够成功地将其循环,但是当我将json元素插入HTML时,它看起来像这样:

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;]'>

我希望它看起来像这样(因为它在原始json字符串中):

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

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

有什么建议吗?

推荐答案

您必须通过safe过滤器过滤该值,以告诉jinja2不应将任何其他过滤器应用于输出.用jinja2语法是:

You must filter the value through the safe filter to tell jinja2 that it shouldn't apply any other filters to the output. In jinja2 syntax this would be:

{{ jsonData | safe }}

请注意,由于您正在调用json.loads,因此实际上不再具有json数据,因此有了python列表对象.因此,当它被序列化时,它与调用unicode(['dogs', 'cats'])相同,后者将为您提供u前缀.您可能不希望实际解析json数据,或者需要手动将列表转换为字符串,而不是让jinja2帮您处理.

Note that since you are calling json.loads you actually do not have json data anymore, you have a python list object. Thus when it is serialized it's the same as calling unicode(['dogs', 'cats']) which is going to give you your u prefix. You might not want to actually parse the json data, or you'll need to turn the list into a string manually instead of having jinja2 do it for you.

这篇关于JSON在Jinja2模板中显示为Unicode实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆