Json 在 django rest api 中使用 POST 解析错误

Json parse error using POST in django rest api

我正在尝试通过 Django REST 框架实现一个简单的 GET/POST api

views.py

class cuser(APIView):
def post(self, request):
   stream  = BytesIO(request.DATA)
    json = JSONParser().parse(stream)
    return Response()

urls.py

from django.conf.urls import patterns, url
from app import views
urlpatterns = patterns('',

           url(r'^challenges/',views.getall.as_view() ),
           url(r'^cuser/' , views.cuser.as_view() ),
      )

我正在尝试 POST 一些 json 到 /api/cuser/ (api 是我项目 urls.py 中的命名空间), JSON

{
"username" : "abhishek",
"email" : "john@doe.com",
"password" : "secretpass"
}

我尝试从可浏览的 API 页面和 httpie(一个 python 制作的类似于 curl 的工具)

httpie command

http --json POST http://localhost:58601/api/cuser/ username=abhishek email=john@doe.com password=secretpass

但我收到 JSON 解析错误:

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

Whole Debug message using --verbose --debug

    POST /api/cuser/ HTTP/1.1

Content-Length: 75

Accept-Encoding: gzip, deflate

Host: localhost:55392

Accept: application/json

User-Agent: HTTPie/0.8.0

Connection: keep-alive

Content-Type: application/json; charset=utf-8



{"username": "abhishek", "email": "john@doe.com", "password": "aaezaakmi1"}

HTTP/1.0 400 BAD REQUEST

Date: Sat, 24 Jan 2015 09:40:03 GMT

Server: WSGIServer/0.1 Python/2.7.9

Vary: Accept, Cookie

Content-Type: application/json

Allow: POST, OPTIONS



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

您 运行 遇到的问题是您的请求已经被解析,而您正在尝试再次解析它。

来自"How the parser is determined"

The set of valid parsers for a view is always defined as a list of classes. When request.data is accessed, REST framework will examine the Content-Type header on the incoming request, and determine which parser to use to parse the request content.

在您的代码中,您正在访问 request.DATA,它是 request.data 的 2.4.x 等价物。因此,一旦您调用它,您的请求就会被解析,并且 request.DATA 实际上会返回您期望解析的字典。

json = request.DATA

确实是解析传入的 JSON 数据所需的全部。您实际上是将 Python 字典传递给 json.loads,它似乎无法解析它,这就是您收到错误的原因。

我通过 Google 到达这个 post for

"detail": "JSON parse error - Expecting property name enclosed in double-quotes": Turns out you CANNOT have a trailing comma in JSON.

因此,如果您遇到此错误,您可能需要像这样更改 post:

{
    "username" : "abhishek",
    "email" : "john@doe.com",
    "password" : "secretpass",
}

对此:

{
    "username" : "abhishek",
    "email" : "john@doe.com",
    "password" : "secretpass"
}

请注意 JSON 对象中最后一个 属性 后删除的 逗号

基本上,每当您尝试使用请求库发出 post 请求时,该库还包含 json 参数,当数据参数设置为文件或数据时,该参数将被忽略。所以基本上当 json 参数设置为 json 数据时。 Headers设置为Content-Type: application/jsonJson 参数基本上 编码数据 发送到 json 格式。因此在 DRF 特别是能够 解析 json 数据。否则在只有数据参数的情况下,它被视为 form-encoded

requests.post(url, json={"key1":"value1"})

您可以在此处找到更多信息request.post complicated post methods