Question

I am trying to pass a dictionary to a django template. In the django view, the variable is initialized and passed as such:

foo = {'a':'b'}
...
return render(request, 'template.html', {'foo': str(foo)}

In the template, I have

{{ foo|default:"{}"|safe}}

In case it's relevant, I have the above line in a jquery snippet. That snippet is failing because the dict is being rendered as

[{'a': u'b'}] 

instead of what I expect:

[{'a': 'b'}] 

It seems the safe filter is not removing the unicode u preceding the dict value 'b'. How do I do that?

Was it helpful?

Solution

You should be using a function to explicitly convert it to JSON, because of a few subtle differences between JSON and the default Python stringification:

  • A string in JSON technically must be delimited with " rather than ', though parsers tend to accept the latter too (see the string rule on json.org)

  • Bool literals are lowercase

  • If your data contains things other than numbers, strings, lists and dicts, using str on them will probably silently produce invalid JSON

Use a template filter such as django-jsonify:

{% load jsonify %}
...
{{ foo|jsonify }}

OTHER TIPS

The reason I was experiencing this problem was because my dictionary actually included a unicode value. The toy example above was a simplification. when i ran str(val) before inserting val into the dict, the rendering occurred as expected.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top