繁体   English   中英

“TypeError”类型的对象不是 JSON 可序列化的

[英]Object of type 'TypeError' is not JSON serializable

我尝试使用 Django 休息框架构建 API

我得到了对象

type 'TypeError' is not JSON serializable

我该怎么做才能解决?

这是我的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 无法将 Exception 对象转换为 JSON 格式并引发错误。 要修复它,您应该将错误转换为字符串并将结果传递给响应:

except Exception as e:
    return Response(str(e), status=status.HTTP_404_NOT_FOUND, template_name=None, content_type=None)

第一的

import json
from django.http import HttpResponse

换线

  return Response(result, status=status.HTTP_200_OK, template_name=None, content_type=None)

为了这

   return HttpResponse(json.dumps(result),content_type="application/json")

或使用

 from django.http import JsonResponse

 return JsonResponse(json.dumps(result))

Python 异常不是 json 可序列化的。 由于某些连接或内容不可用问题, try失败,然后进入您将异常e传递给Response()except块,这样就产生了问题。 解决方案 - 检查 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM