[Fixed]-JSON is appearing as unicode entities in Jinja2 template

22👍

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.

1👍

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 }} 
👤M. F.

0👍

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>
👤phyatt

Leave a comment