About Rendering a Python Dictionary as JSON

Create a simple template filter to_json to convert Python lists and dictionaries to JSON in your templates:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# core/templatetags/core_filters.py
from django import template

register = template.Library()

@register.filter
def to_json(value):
    import json
    from django.core.serializers.json import DjangoJSONEncoder
    from django.utils.safestring import mark_safe
    return mark_safe(json.dumps(value, cls=DjangoJSONEncoder))

Then you can use the filter for an attribute of an HTML tag

1
2
3
{% load core_filters %}

<div data-config='{{ config|to_json }}'></div>

or a JavaScript variable:

1
2
3
4
5
{% load core_filters %}

<script>
    const config = {{ config|to_json }};
</script>

Tips and Tricks Programming Development Django 4.2 Django 3.2 Django 2.2 Python 3 JavaScript HTML5