JavaScript fetch to Django view: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Question:

I have a JavaScript fetch to call a URL to pass data into my Django view to update a value for the user.

Error in views.py:

Traceback (most recent call last):
  File "C:Python310libsite-packagesdjangocorehandlersexception.py", line 47, in inner
    response = get_response(request)
  File "C:Python310libsite-packagesdjangocorehandlersbase.py", line 181, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:Python310libsite-packagesdjangocontribauthdecorators.py", line 21, in _wrapped_view
    return view_func(request, *args, **kwargs)
  File "C:UsersrosswDocumentsProjectsScryappsadministrationviews.py", line 47, in administration_users_page
    switchData = json.load(request)['switch']
  File "C:Python310libjson__init__.py", line 293, in load
    return loads(fp.read(),
  File "C:Python310libjson__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "C:Python310libjsondecoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "C:Python310libjsondecoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

Error in browser:

0
PUT http://127.0.0.1:8000/administration/users/JM/ 500 (Internal Server Error)
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON

JavaScript:

const changeAdminUserAction = (id,data) => {
    console.log(data)
    fetch(`/administration/users/${id}/`,{
        method: 'PUT',
        body: JSON.stringify({type: "adminUser", switch: data}),
        headers: {'X-CSRFToken' : csrfToken, 'Content-Type': 'application/json'},
    })
    .then((response) => response.json())
    .then((result) => {location.reload()})
    .catch((err) => {console.log(err)})
}

views.py:

    if request.method == 'PUT':
        user = CustomUser.objects.get(username=kwargs.get('username'))
        
        switchType = json.load(request)['type']
        switchData = json.load(request)['switch']
        print(switchType, switchData)
        
        if switchType == 'adminUser':
            user.admin_user = switchData
        elif switchType == 'admindata':
            user.admin_data = switchData
        elif switchType == 'Status':
            if user.status == COMMON.USER_ACTIVE:
                user.status = COMMON.USER_SUSPENDED
            else:
                user.status = COMMON.USER_ACTIVE
            user.failed_logins = 0

        user.save()
        return JsonResponse({})

This is throwing an error at switchData = json.load(request)['switch']. I don’t know why it is throwing the error there as the previous line switchType = json.load(request)['type'] works as expected and returns the value that was passed to it.

data is a integer – either 1 or 0. I have tried make this value a string but it throws the same error.

Asked By: Ross

||

Answers:

Shouldn’t json.load(request)['switch'] be json.load(request.body)['switch']?

Answered By: Stanley Ulili

I cannot explain why this happens, but its clearly related to the form how you are reading your data. It will also break at switchType = json.load(request)['type'] if you invert the lines (Seems to break while reading the second argument).

Data comes in as bytes, you can decode them into string (source) and parse into JSON, this method worked well in my testing:

if request.method == 'PUT':
    decoded_bytes = request.body.decode("utf-8")
    data = json.loads(decoded_bytes)
    switchType = data['type']
    switchData = data['switch']
    print(switchType, switchData)
    ...

    return JsonResponse({})
Answered By: Niko
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.