Django json.loads(request.body)给出错误Expecting value:第1行第1列

时间:2017-12-03 18:25:52

标签: javascript jquery python json django

我试图将JSON数据推送到我的Django View,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 View

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 Log

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 个答案:

答案 0 :(得分: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>