How can I iterate over this to get get MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, and all the value in the ‘item’ list for instance value for PhoneNumber. Am getting this data from a callBackURl after a user makes a payment.
"Body":{ "stkCallback":{ "MerchantRequestID":"19465-780693-1", "CheckoutRequestID":"ws_CO_27072017154747416", "ResultCode":0, "ResultDesc":"The service request is processed successfully.", "CallbackMetadata":{ "Item":[ { "Name":"Amount", "Value":1 }, { "Name":"MpesaReceiptNumber", "Value":"LGR7OWQX0R" }, { "Name":"Balance" }, { "Name":"TransactionDate", "Value":20170727154800 }, { "Name":"PhoneNumber", "Value":254721566839 } ] } } } }``` I want to get MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, and all the value in the list 'item' then store them in the db. ```new_user = MpesaResponses(MerchantRequestID=data[0]['Body']['stkCallback']['MerchantRequestID'], CheckoutRequestID=data[0]['Body']['stkCallback']['CheckoutRequestID'], ResultCode=data[0]['Body']['stkCallback']['ResultCode'], ResultDesc=data[0]['Body']['stkCallback']['ResultDesc'], Amount=data[0]['Body']['stkCallback']['CallbackMetadata']['Item'][0] ['value'], MpesaReceiptNumber=data[0]['Body']['stkCallback']['CallbackMetadata'] ['Item'][1]['value'], TransactionDate=data[0]['Body']['stkCallback']['CallbackMetadata']['Item'] [3]['value'], PhoneNumber=data[0]['Body']['stkCallback']['CallbackMetadata']['Item'][4] ['value']) db.session.add(new_user) db.session.commit()``` This is what I had tried.
Advertisement
Answer
If the data is just a dictionary starting at "Body"
and not a list containing a dictionary, then just remove the first [0]
from each variable, then check your spelling on Value
as so:
MerchantRequestID=data['Body']['stkCallback']['MerchantRequestID'] CheckoutRequestID=data['Body']['stkCallback']['CheckoutRequestID'] ResultCode=data['Body']['stkCallback']['ResultCode'] ResultDesc=data['Body']['stkCallback']['ResultDesc'] Amount=data['Body']['stkCallback']['CallbackMetadata']['Item'][0]['Value'] MpesaReceiptNumber=data['Body']['stkCallback']['CallbackMetadata']['Item'][1]['Value'] TransactionDate=data['Body']['stkCallback']['CallbackMetadata']['Item'][3]['Value'] PhoneNumber=data['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value']