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:

# 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

{% load core_filters %}

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

or a JavaScript variable:

{% 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