0

I am getting a JSON Decode error at /charge when data = json.loads(request.body). I am working with stripe api as well as fetch api.

The full error is this:

Traceback (most recent call last):
  File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner
    response = get_response(request)
  File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/antariksh/Desktop/Python Files/Owlet/env/lib/python3.7/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "/home/antariksh/Desktop/Python Files/Owlet/Menu/views.py", line 151, in charge
    data = json.loads(request.body)
  File "/usr/lib/python3.7/json/__init__.py", line 348, in loads
    return _default_decoder.decode(s)
  File "/usr/lib/python3.7/json/decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib/python3.7/json/decoder.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)

That is the error. My code for the /charge/ view is this:

@csrf_exempt
def charge(request):
    if request.method == 'POST':
        print(request.POST)

        transaction_id = uuid.uuid4().hex
        data = json.loads(request.body)
        print(data)

        if request.user.is_authenticated:
            customer = request.user.customer
            order, created = Order.objects.get_or_create(customer=customer, isComplete=False, status='Created')

        else:
            order, customer = guestOrder(request, data)

        total = data['form']['total']
        order.transaction_id = transaction_id
        order.isComplete = True
        order.status = 'Accepted'
        order.save()

        ShippingAddress.objects.create(
                customer = customer,
                order = order,
                address = data['shipping']['address'],
                city = data['shipping']['city'],
                state = data['shipping']['state'],
                zipcode = data['shipping']['zipcode'],
            )
    
    mailOrder(data['form']['email'], order)

    return redirect(reverse('menupage'))

The JSON is fine since I checked everything which is parsed and when I ran the code. It saves the data in the database but still shows the error page. The javascript is this:

var url = '/charge/'

            fetch(url, {
                method:'POST',
                headers:{
                    'Content-Type':'application/json',
                    'X-CSRFToken': csrftoken
                }, 
                body:JSON.stringify({'form':userData, 'shipping':shippingData}),
            })

            .then((response) => {
                response.json()
                })

            .then((data) => {
                console.log(data)
                swal({
                    icon: "success",
                    text: "Transaction Completed"
                });

                cart = {}
                document.cookie = 'cart=' + JSON.stringify(cart) + ";domain=;path=/"
            });

The above javascript is fine in terms of syntax. If there is some problem in JSON or anything please help. Help is much appreciated. Please look and tell me what is wrong. Any advice is also much appreciated. I haven't shared the stripe API code.

yum
  • 1,125
  • 1
  • 8
  • 14
  • What is your exact version of python? Can you do a `print(request.body)` before the error and add that to your question? https://stackoverflow.com/a/29781023/11199887 – kcontr Jul 01 '20 at 15:44
  • Your error is specifically consistent with trying to parse an empty string "" with `json.loads("")` so seeing the output of request.body would be helpful to verify that is the case – kcontr Jul 01 '20 at 16:00

0 Answers0