You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Rest Framework JSON解析器不接受字符串为有效JSON的问题咨询

问题原因与解决方案

1. 前端请求的核心问题

你直接发送"test"字符串作为请求体时,实际传输的内容是裸字符串test,这不符合JSON规范——JSON的顶层字符串值必须被双引号包裹(即传输内容应为"test",而非test)。DRF的默认JSON解析器使用Python标准库的json.loads(),该函数无法解析裸字符串,因此抛出JSON parse error。

前端修正方法

使用JSON.stringify()将字符串序列化为合法的JSON格式,并确保明确设置Content-Type请求头:

return axios
  .post(API_URL + 'create/', 
    JSON.stringify("test"), // 关键:序列化字符串为合法JSON
    {
      headers: {
        ...headers,
        'Content-Type': 'application/json'
      }
    }
  )
  .then(response => {
    return response.data;
  })
  .catch((error) => {
    console.log(error);
  });

2. 后端的适配处理

即使前端发送了合法的JSON字符串,你的ListCreateAPIView默认依赖MySerializer处理请求数据,而ModelSerializer通常期望接收键值对象(对应模型字段),而非顶层字符串。需要修改post方法来兼容字符串输入:

from rest_framework import status
from rest_framework.response import Response

class ObjectList(ListCreateAPIView):
    """
    View dedicated to GET a list of instances or POST a new one
    """
    serializer_class = MySerializer
    authentication_classes = [JWTAuthentication]
    permission_classes = [IsAuthenticated]

    def get_queryset(self):
        queryset = MyObject.objects.filter(user=self.request.user)
        return queryset
    
    def post(self, request, format=None):
        # 处理顶层字符串输入
        if isinstance(request.data, str):
            # 根据你的模型需求,将字符串存入对应字段
            MyObject.objects.create(user=self.request.user, your_field=request.data)
            return Response({"message": "Instance created successfully"}, status=status.HTTP_201_CREATED)
        # 原逻辑处理键值对象输入
        return super().post(request, format)

补充说明

RFC 8259确实允许JSON顶层值为字符串,但DRF的默认解析器仅在请求体是合法JSON时才能解析,而前端的原始写法没有生成合法的JSON字符串。同时,视图的序列化器默认适配模型的结构,需要手动添加字符串输入的处理逻辑。

内容的提问来源于stack exchange,提问作者Beinje

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 16:36:20