python __proxy__ is not JSON serializable

2020-03-05 15:00:35 浏览数 (1)

详细错误如下

代码语言:javascript复制
TypeError at /
Object of type __proxy__ is not JSON serializable
Request Method: GET
Request URL:    http://127.0.0.1:8000/
Django Version: 2.2.2
Exception Type: TypeError
Exception Value:    
Object of type __proxy__ is not JSON serializable
Exception Location: /Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/json/encoder.py in default, line 179
Python Executable:  /Users/panjing/PycharmProjects/simpleui_demo/venv/bin/python
Python Version: 3.7.1
Python Path:    
['/Users/panjing/PycharmProjects/simpleui_demo',
 '/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Users/panjing/PycharmProjects/simpleui_demo',
 '/Applications/PyCharm.app/Contents/helpers/pycharm_display',
 '/Applications/PyCharm.app/Contents/helpers/third_party/thriftpy',
 '/Applications/PyCharm.app/Contents/helpers/pydev',
 '/Users/panjing/Library/Caches/PyCharm2019.1/cythonExtensions',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python37.zip',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7',
 '/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/lib-dynload',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/setuptools-39.1.0-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/xadmin-0.6.1-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/six-1.12.0-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/future-0.17.1-py3.7.egg',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/django_reversion-3.0.4-py3.7.egg',
 '/Applications/PyCharm.app/Contents/helpers/pycharm_matplotlib_backend',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf',
 '/Users/panjing/PycharmProjects/simpleui_demo/venv/lib/python3.7/site-packages/odf']

原因 对象是Promise,所以直接json序列话会报错

加一个自定义的解码类就可以了

代码语言:javascript复制
from django.utils.functional import Promise
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)


json.dumps(data,cls=DjangoJSONEncoder)      

参考资料

  • https://docs.djangoproject.com/en/dev/ref/unicode/#translated-strings

0 人点赞