2

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.

2
  • what if you use request.POST or request.GET instead of request.body Commented Jun 1, 2021 at 9:38
  • The view is a callback url where an API is sending me POST json data Commented Jun 1, 2021 at 9:42

5 Answers 5

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Hello, I've tried this but it yields a JSONDecodeError Expecting value: line 1 column 1 (char 0)
print(request.POST) and check it's type if your method is post. Reply it here let's continue debugging.
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.

Comments

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)

Comments

0

I was young and this code is quite pathetic :)

If facing a similar problem, Python comes with a builtin module to handle json serialization/deserialization. How to use this is as below.

import json

data = b'{"byte":"string"}'

# Serialize to json
jsoned_data = json.loads(data encoding='utf-8')

# Deserialize from json
unjsoned_data = json.dumps(jsoned_data, indent=2)

Comments

-1

Use json() method.

data = request.json()

2 Comments

Hi, that produces AttributeError: 'WSGIRequest' object has no attribute 'json'
This is for python requests library. It can't be used for Django.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.