Skip to content
Advertisement

django, “is not JSON serializable” when using ugettext_lazy?

I have this in my views.py

response_dict = {
    'status': status,
    'message': message
}
return HttpResponse(simplejson.dumps(response_dict),
                    mimetype='application/javascript')

Since I start using this import:

from django.utils.translation import ugettext_lazy as _

at this line:

message = _('This is a test message')

I get this error:

 File "/home/chris/work/project/prokject/main/views.py", line 830, in fooFunc
    return HttpResponse(simplejson.dumps(response_dict),

  File "/usr/local/lib/python2.7/json/__init__.py", line 243, in dumps
    return _default_encoder.encode(obj)

  File "/usr/local/lib/python2.7/json/encoder.py", line 207, in encode
    chunks = self.iterencode(o, _one_shot=True)

  File "/usr/local/lib/python2.7/json/encoder.py", line 270, in iterencode
    return _iterencode(o, 0)

  File "/usr/local/lib/python2.7/json/encoder.py", line 184, in default
    raise TypeError(repr(o) + " is not JSON serializable")

TypeError: <django.utils.functional.__proxy__ object at 0x7f42d581b590> is not JSON serializable

Why? What am I doing wrong?

Advertisement

Answer

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')
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement