[Django]-Django, "is not JSON serializable" when using ugettext_lazy?

58👍

You can also create you own JSON encoder that will force __proxy__ to unicode.

From https://docs.djangoproject.com/en/1.8/topics/serialization/

from django.utils.functional import Promise
from django.utils.encoding import force_text
from django.core.serializers.json import DjangoJSONEncoder

class LazyEncoder(DjangoJSONEncoder):
    def default(self, obj):
        if isinstance(obj, Promise):
            return force_text(obj)
        return super(LazyEncoder, self).default(obj)

So now your code can look like:

response_dict = {
    'status': status,
    'message': _('Your message')
}

return HttpResponse(json.dumps(response_dict, cls=LazyEncoder),
                    mimetype='application/javascript')
👤utek

24👍

It’s not a string yet, and Python’s JSON encoder doesn’t know about ugettext_lazy, so you’ll have to force it to become a string with something like

response_dict = {
    'status': status,
    'message': unicode(message)
}

0👍

You can custom JSONEncoder or use str as default serialize method:

# Created by BaiJiFeiLong@gmail.com at 2022/3/28
import json
from json import JSONEncoder
from typing import Any

import django
from django.conf import settings
from django.utils.translation import gettext_lazy as _

settings.configure()
django.setup()


class MyEncoder(JSONEncoder):
    def default(self, o: Any) -> Any:
        if getattr(type(o), "_delegate_text", False):
            return str(o)
        return super().default(o)


print(json.dumps(dict(hello=_("world")), default=str))
print(json.dumps(dict(hello=_("world")), cls=MyEncoder))

Leave a comment