我正在尝试启动并运行已经适用于其他人的API(当然,我现在无法咨询)。我得到一个特定端点的错误:
TypeError: dict_values([
{'unregistered_users': 2, 'group_name': 'a', 'registered_users': 9, 'total_users': 11},
{'unregistered_users': 0, 'group_name': 'b', 'registered_users': 4, 'total_users': 4},
{'unregistered_users': 0, 'group_name': 'c', 'registered_users': 4, 'total_users': 4},
{'unregistered_users': 4, 'group_name': 'd', 'registered_users': 5, 'total_users': 9},
{'unregistered_users': 0, 'group_name': 'e', 'registered_users': 7, 'total_users': 7},
{'unregistered_users': 0, 'group_name': 'f', 'registered_users': 7, 'total_users': 7}]) is not JSON serializable
据我所知,这是有效的JSON,没有理由不能将其序列化。我已经仔细研究了其他关于缺少JSON可串行性的SO问题,并且找不到任何关于为什么这不起作用的提示。我的堆栈跟踪:
File "/Users/AJ/code/my_app/events/views/event_views.py", line 50, in get
return JsonResponse(event)
File "/usr/local/lib/python3.5/site-packages/django/http/response.py", line 530, in __init__
data = json.dumps(data, cls=encoder, **json_dumps_params)
File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/__init__.py", line 237, in dumps
**kw).encode(obj)
File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 198, in encode
chunks = self.iterencode(o, _one_shot=True)
File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 256, in iterencode
return _iterencode(o, 0)
File "/usr/local/lib/python3.5/site-packages/django/core/serializers/json.py", line 121, in default
return super(DjangoJSONEncoder, self).default(o)
File "/usr/local/Cellar/python3/3.5.2/Frameworks/Python.framework/Versions/3.5/lib/python3.5/json/encoder.py", line 179, in default
raise TypeError(repr(o) + " is not JSON serializable")
使用OS X,Python 3.5,Django 1.11和带有UTF-8编码FWIW的Postgres DB。不知道在哪里继续进行故障排除。
抛出错误的代码:
from django.http import JsonResponse, HttpResponseNotFound, HttpResponseForbidden
...
@method_decorator([need_jwt_verification, csrf_exempt], name="dispatch")
class EventController(View):
def get(self, request, id):
event = self.eventService.get_event_details(id)
...
return JsonResponse(event)