[英]Object of type 'TypeError' is not JSON serializable
I try to build API with Django rest framework我尝试使用 Django 休息框架构建 API
And I got Object of我得到了对象
type 'TypeError' is not JSON serializable
What should I do to fix?我该怎么做才能解决?
Here's my view.py
这是我的
view.py
class NewsViewSet(viewsets.ModelViewSet):
queryset = News.objects.all()
serializer_class = NewsSerializer
def list(self, request, **kwargs):
try:
nba = query_nba_by_args(**request.query_params)
serializer = NewsSerializer(nba['items'], many=True)
result = dict()
result['data'] = serializer.data
result['draw'] = nba['draw']
result['recordsTotal'] = nba['total']
result['recordsFiltered'] = nba['count']
return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)
except Exception as e:
return Response(e, status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
Django cannot convert Exception object to JSON format and raise error. Django 无法将 Exception 对象转换为 JSON 格式并引发错误。 To fix it you should convert error to string and pass result to response:
要修复它,您应该将错误转换为字符串并将结果传递给响应:
except Exception as e:
return Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
first第一的
import json
from django.http import HttpResponse
Change line换线
return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)
for this为了这
return HttpResponse(json.dumps(result),content_type="application/json")
or use或使用
from django.http import JsonResponse
return JsonResponse(json.dumps(result))
Python exceptions are not json serializable. Python 异常不是 json 可序列化的。 It's failing in
try
because of some connection or content unavailable issue, then going into except
block where you are passing exception e
as it is to Response()
so that is creating the issue.由于某些连接或内容不可用问题,
try
失败,然后进入您将异常e
传递给Response()
的except
块,这样就产生了问题。 Solution - check the URL and also in except block convert exception e
to string and pass to Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
.解决方案 - 检查 URL 并在 except 块中将异常
e
转换为字符串并传递给Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.