JSON 在 Jinja2 模板中显示为 unicode 实体
我将 Jinja2 与 webapp2 一起使用。
正如他们的文档所说,Jinja2 将所有“上下文”数据编码为 unicode。当我尝试将 json 字符串插入到模板中时,这被证明是有问题的:
jsonData = json.loads(get_the_file('catsJson.txt'))
我将 jsonData 传递给模板,并且能够成功循环它,但是当我将 json 元素插入到 HTML 中时,它看起来像这样:
<option value='[u'dogs', u'cats']'>
我希望它看起来像这样(因为它在原始 json 字符串中):
<option value='["dogs", "cats"]'>
有什么建议吗?
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'dogs', u'cats']'>
I want it to look like this (as it is in the original json string):
<option value='["dogs", "cats"]'>
Any suggestions?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您必须通过
safe
过滤器过滤该值,以告诉 jinja2 它不应将任何其他过滤器应用于输出。在 jinja2 语法中,这将是:请注意,由于您正在调用 json.loads,您实际上不再拥有 json 数据,而是拥有一个 python 列表对象。因此,当它被序列化时,它与调用
unicode(['dogs', 'cats'])
相同,这将为您提供u
前缀。您可能不想实际解析 json 数据,或者您需要手动将列表转换为字符串,而不是让 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: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 callingunicode(['dogs', 'cats'])
which is going to give you youru
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.在 Jinja 2.9 中,我遵循 @Xion 的建议,首先使用
map('string')
将可迭代元素转换为字符串。然后,我将地图过滤结果转换为一个列表,最终使用tojson
内置过滤器将其输出为 JSON。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 thetojson
built-in filter.如果您不需要对 Jinja 端的数组进行操作,而只需将数据包传递给 javascript,我建议使用:
https://docs.python.org/2/library/json.html
这个字符串化变量,当传递到 jinja 时,会传递到 javascript,而不会获得 pythonic unicode变量上的标记。顺便说一句,可能会将
True
和False
修复为true
和false
,正如 javascript 所期望的那样。所以在 Flask 的上下文中,它看起来像这样:
home.html
If you don't need to act on the array in the Jinja side, but just need to pass the packet to javascript, I would recommend using:
https://docs.python.org/2/library/json.html
This stringified variable, when passed into jinja gets passed down to javascript without getting the pythonic unicode markings on variables. And incidentally, will likely fix
True
andFalse
getting fixed totrue
andfalse
as javascript would expect.So in the context of flask, it would look something like this:
home.html