Django json.loads(request.body) 给出错误期望值:第 1 行第 1 列

Posted

技术标签:

【中文标题】Django json.loads(request.body) 给出错误期望值:第 1 行第 1 列【英文标题】:Django json.loads(request.body) gives error Expecting value: line 1 column 1 【发布时间】:2018-05-17 05:32:39 【问题描述】:

我正在尝试将 JSON 数据推送到我的 Django 视图,GET 工作正常,但每次我尝试使用 json.loads(request.body) 处理推送数据时,我都会得到

raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

我的 javascript

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () 
    var post = function () 

        $.ajax(
            type: "POST",
            contentType: "application/json",
            url: "http://127.0.0.1:8000/app/input",
            data: first_name: "Test", status: "testing",
            dataType: "json"
        );
    ;
    post();
)
</script>

浏览器的console.log是

"baz": "goo", "foo": "bar" jquery-3.2.1.min.js:4
POST http://127.0.0.1:8000/app/input 500 (Internal Server Error)

Django 视图

from django.http import HttpResponseRedirect, HttpResponse, JsonResponse
from django.views.decorators.csrf import csrf_exempt
import json

# Create your views here.
@csrf_exempt
def input(request):
    if request.method == 'GET':
        data = 'baz': 'goo', 'foo': 'bar'
        data = json.dumps(data)
        return HttpResponse(json.dumps(data), content_type='application/json')
    else:
        data = request.body
        print(request.body) #b'first_name=Test&status=testing'
        print(type(request.body)) #<class 'bytes'>
        decodebody = request.body.decode('utf-8')
        print(decodebody) #first_name=Test&status=testing
        print(type(decodebody)) #<class 'str'>
        jsondata = json.loads(data)
        print(jsondata)
        print(type(jsondata))
        return HttpResponse(data, content_type='application/json')

Django 日志

b'first_name=Test&status=testing'
<class 'bytes'>
first_name=Test&status=testing
<class 'str'>
[03/Dec/2017 13:00:49] "GET /app/input HTTP/1.1" 200 38
Internal Server Error: /app/input
Traceback (most recent call last):
  File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 41, in inner
    response = get_response(request)
  File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 187, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\core\handlers\base.py", line 185, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\site-packages\django\views\decorators\csrf.py", line 58, in wrapped_view
    return view_func(*args, **kwargs)
  File "C:\Users\onwar\PycharmProjects\JSONServer\computermanager\views.py", line 21, in input
    jsondata = json.loads(data)
  File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\json\__init__.py", line 354, in loads
    return _default_decoder.decode(s)
  File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 339, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:\Users\onwar\AppData\Local\Programs\Python\Python36-32\lib\json\decoder.py", line 357, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)
[03/Dec/2017 13:00:49] "POST /app/input HTTP/1.1" 500 84429

我目前正在研究是否可以传递 JSON 并在返回它之前修改名称,但我一直坚持这个错误。如果您需要更多信息或有任何疑问,请告诉我。

【问题讨论】:

【参考方案1】:

异常json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) 告诉您json.loads 无法解析request.body(因为您没有发送JSON)。使用JSON.stringify 将您的数据对象转换为JSON 字符串。

json.loads 需要 JSON 字符串,这就是您需要使用 JSON.stringify 的原因。

<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$(document).ready(function () 
    var post = function () 

        $.ajax(
            type: "POST",
            contentType: "application/json",
            url: "http://127.0.0.1:8000/app/input",
            data: JSON.stringify(first_name: "Test", status: "testing"),
            dataType: "json"
        );
    ;
    post();
)
</script>

【讨论】:

以上是关于Django json.loads(request.body) 给出错误期望值:第 1 行第 1 列的主要内容,如果未能解决你的问题,请参考以下文章

Django 无法通过request.POST.get()获取数据的问题

django-腾讯paas-appengine阅读

django请求报错JSONDecodeError

从 django 模板访问 JSON 属性

Django 序列化对象返回数组

Python json.loads()