"JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"



我正在用Django Rest Framework创建一个项目,遇到了一些问题,无法解决。

所以,我有一个张贴方法的URL,当我用邮递员在那里张贴时,我会得到一个错误:

{
"detail": "JSON parse error - Expecting property name enclosed in double quotes: line 1 column 2 (char 1)"
}

这是正在发送的数据:

{username:"REQUAB", password:"REQUAB", emailId:"requab@gmail.com"}

只是为了检查我在序列化程序或模型中是否有问题,我做了一个正常的get请求,得到了正确的输出。

我的模型.py:

from django.db import models
# Create your models here.
class User(models.Model):
emailId = models.EmailField(max_length=50)
username = models.CharField(max_length=20)
password = models.CharField(max_length=50)
recipes = models.IntegerField(default=0)
def __str__(self):
return self.username

我的序列化程序.py:

from rest_framework import serializers
from .models import User
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'emailId', 'password', 'recipes']

myurls.py:

from django.urls import path
from .views import UsersList, UsersDetail
urlpatterns = [
path('', UsersList.as_view()),
]

我的观点.py:

from django.http import Http404
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from users.models import User
from .serializers import UserSerializer
# Create your views here.
class UsersList(APIView):
def get(self, request, format=None):
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)

def post(self, request):
print(request.data)
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

请帮我(谢谢,提前(。

错误很明显,请尝试将属性名称用双引号括起来,或者在发送时使用JSON.stringify(使用JS(。

我在尝试通过向drf端点发布json数据来测试它时遇到了这个错误。解决方案是用json.dumps({...})包装json数据。例如:

import json
def test_webhook_endpoint_exists(self):
response = self.client.post('/webhook/', json.dumps({"key": "value"}), content_type='application/json')
self.assertNotEqual(response.status_code, 404)

相关内容

最新更新