About JSON Out of a Dictionary with Lazy Strings

Use DjangoJSONEncoder to support lazy translations while converting a dictionary to JSON:

# greetings/views.py
import json
from django.shortcuts import render
from django.core.serializers.json import DjangoJSONEncoder
from django.utils.translation import gettext_lazy as _

TRANSLATIONS = {
    "Good afternoon": _("Good afternoon!"),
    "Good evening": _("Good evening!"),
    "Good night": _("Good night!"),
}

def greetings(request):
    context = {
        "translations_json": json.dumps(
            TRANSLATIONS, cls=DjangoJSONEncoder
        ),
    }
    return render(request, "greetings/greetings.html", context)

Tips and Tricks Programming Django 5.x Django 4.2 Django 3.2 Python 3