简体   繁体   中英

Django json.loads(request.body) gives error Expecting value: line 1 column 1

I'm trying to push JSON data to my Django View, GET is working fine but every time I try to process the push data with json.loads(request.body) I get

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

My 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>

The console.log for the browser is

{"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

I'm currently just working on seeing if I can pass JSON and modify the name before returning it, but I've been stuck on this on error. If you need any more info or have any questions please let me know.

The exeption json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) is telling you json.loads cannot parse request.body (becasue you are not sending JSON ). Use JSON.stringify to convert your data object to JSON string.

json.loads expects a JSON string, that's why you need to use 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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM