24

我有这个在我的views.py

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

自从我开始使用这个导入:

from django.utils.translation import ugettext_lazy as _

在这一行:

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

我收到此错误:

 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

为什么?我究竟做错了什么?

4

2 回答 2

55

您还可以创建自己的 JSON 编码器,强制__proxy__转换为 unicode。

来自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)

所以现在你的代码看起来像:

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

return HttpResponse(json.dumps(response_dict, cls=LazyEncoder),
                    mimetype='application/javascript')
于 2015-07-31T12:30:43.110 回答
24

它还不是一个字符串,Python 的 JSON 编码器不知道 ugettext_lazy,所以你必须强制它变成一个字符串,比如

response_dict = {
    'status': status,
    'message': unicode(message)
}
于 2013-11-01T20:20:47.353 回答