1

Below is a view in python Django and output it gives

Code

@csrf_exempt
def stk_push_callback(request):

    data = request.body
    print(data)

    got_data = json.loads(data.decode("utf-8"))

    result_code = got_data['Body']['stkCallback']['ResultCode']
    result_desc = got_data['Body']['stkCallback']['ResultDesc']

    print(' ')
    print('ResultCode: ', result_code)
    print(result_desc)
    print(' ')

    room = room_val()
    check_in = in_val()
    check_out = out_val()
    user = user_val()

    if result_code == 0:
        booking = book_room(user, room, check_in, check_out)
        print (booking)
    
        return render(request, 'booking/paymentcomplete.html')

    else:
        return render(request, 'booking/paymenterror.html')

Output print(data)

b'{"Body":{"stkCallback":{"MerchantRequestID":"9088-17223944-1","CheckoutRequestID":"ws_CO_310520212138262746","ResultCode":1032,"ResultDesc":"Request cancelled by user"}}}'

How do i convert the output to json and also how do i access the "ResultCode":1032 value for further processing? Regards.

Roy Thande
  • 98
  • 2
  • 9

4 Answers4

0

I'm with phone and it's hard to explain more.

import json
data = request.body
data_dict = json.loads(data.decode("utf-8")) 
print(data_dict['Body']['stkCallback']['ResultCode']) 

For more information check How to convert bytes type to dictionary? answer.

mehdi
  • 1,100
  • 1
  • 11
  • 27
  • Hello, I've tried this but it yields a JSONDecodeError Expecting value: line 1 column 1 (char 0) – Roy Thande May 31 '21 at 20:03
  • `print(request.POST)` and check it's type if your method is post. Reply it here let's continue debugging. – mehdi Jun 02 '21 at 05:39
0

Use json() method.

data = request.json()
Sergey Pugach
  • 5,561
  • 1
  • 16
  • 31
0

You are not actually far from the solution.

request.post handles post data via an html form.

While request.body gives you a raw HTTP request body as a bytestring. You can convert into a dictionary using json.loads().

I used got_data = json.loads(data) and it worked as expected.

data was converted to a Python dictionary and so you can do dict related operations on it,

result_code = got_data['Body']['stkCallback']['ResultCode']

More detailed blog post here.

0

if you are using GET method you can do this

exm.html

<input type="text" name="test1" >

views.py

test1 = request.GET["test1"]
dataJson = json.dumps({"test1":test1})

if you are using POST method you can do this

from urllib.parse import unquote
import json

data = request.body
data = str(data, encoding='utf-8')
data = unquote(data)
data = json.loads(data)
MR.code
  • 175
  • 1
  • 14