'TypeError' 类型的对象不是 JSON 可序列化的 [英] Object of type 'TypeError' is not JSON serializable

查看:88
本文介绍了'TypeError' 类型的对象不是 JSON 可序列化的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用 Django rest 框架构建 API

I try to build API with Django rest framework

我得到了

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 格式并引发错误.要修复它,您应该将错误转换为字符串并将结果传递给响应:

Django cannot convert Exception object to JSON format and raise error. 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)

这篇关于'TypeError' 类型的对象不是 JSON 可序列化的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆