Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSONDecodeError Django

Tags:

python

django

I have an API that is sending me a POST request (JSON) for testing. I was doing a lot with the JSON, but all of a sudden it stopped working and giving me a JSONDecodeError. I tried all sorts of things, like using request.POST but nothing worked correctly like I said this was working at one point. Any assistance is appreciated.

Test that gives the error: In the Windows Command prompt, running:

curl -X POST http://127.0.0.1:8000/webhook/webhook_receiver/ -d '{"foo": "bar"}'

Error: json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

View:

def webhook_receiver(request, *args, **kwargs):
    if request.method == 'POST':
        # Get the incoming JSON Data
        data = request.body.decode('utf-8')
        received_json_data = json.loads(data)
        return HttpResponse(received_json_data)
    else:
        return HttpResponse("not Post")
like image 595
Jiroscopes Avatar asked Sep 20 '25 23:09

Jiroscopes


1 Answers

The culprit is the combination of your command quoting syntax and the Windows terminal interpreter (what you posted would have been fine using Bash for example).

See Escaping curl command in Windows for details.


The actual error (which you really ought to have posted) looks like this:

Exception Type: JSONDecodeError at /webhook/webhook_receiver/
Exception Value: Expecting value: line 1 column 1 (char 0)

That says the data you are passing into the decoder does not start with a valid character (such as a "{" if the JSON is supposed to be a dict, or "[" for an array). You can probably work out what the problem is really easily by adding a print() for the start of the data, e.g. like:

print('first few characters=<{}>'.format(data[:4]))
like image 192
Shaheed Haque Avatar answered Sep 22 '25 11:09

Shaheed Haque