JSON is appearing as unicode entities in Jinja2 template

心已入冬 提交于 2019-12-18 19:04:31

问题


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?


回答1:


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 }}

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.




回答2:


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 }} 



回答3:


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:

json.dumps(python_object_or_array)

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 and False getting fixed to true and false as javascript would expect.

So in the context of flask, it would look something like this:

@app.route('/')
def home():
     if userNeedsToLogin():
          session['routePath'] = request.full_path
          return render_template('login.html', error=None)
     else:
          return render_home()

def render_home():
     print "Rendering Home"
     results = get_some_database_query_results()
     data_out = json.dumps(results)
     return render_template('home.html', data=data_out)

home.html

<!DOCTYPE HTML>
<html>
<head>
  <!-- import javascript function processData -->
</head>
<body>
  <!-- page of stuff -->
  <script>
     processData( {{ data|safe }} );
  </script>
</body>
</html>


来源:https://stackoverflow.com/questions/8710758/json-is-appearing-as-unicode-entities-in-jinja2-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!