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.
JavaScript
x
51
51
1
"Body":{
2
"stkCallback":{
3
"MerchantRequestID":"19465-780693-1",
4
"CheckoutRequestID":"ws_CO_27072017154747416",
5
"ResultCode":0,
6
"ResultDesc":"The service request is processed successfully.",
7
"CallbackMetadata":{
8
"Item":[
9
{
10
"Name":"Amount",
11
"Value":1
12
},
13
{
14
"Name":"MpesaReceiptNumber",
15
"Value":"LGR7OWQX0R"
16
},
17
{
18
"Name":"Balance"
19
},
20
{
21
"Name":"TransactionDate",
22
"Value":20170727154800
23
},
24
{
25
"Name":"PhoneNumber",
26
"Value":254721566839
27
}
28
]
29
}
30
}
31
}
32
}```
33
34
I want to get MerchantRequestID, CheckoutRequestID, ResultCode, ResultDesc, and all the value in the list
35
'item' then store them in the db.
36
```new_user = MpesaResponses(MerchantRequestID=data[0]['Body']['stkCallback']['MerchantRequestID'],
37
CheckoutRequestID=data[0]['Body']['stkCallback']['CheckoutRequestID'],
38
ResultCode=data[0]['Body']['stkCallback']['ResultCode'],
39
ResultDesc=data[0]['Body']['stkCallback']['ResultDesc'],
40
Amount=data[0]['Body']['stkCallback']['CallbackMetadata']['Item'][0]
41
['value'],
42
MpesaReceiptNumber=data[0]['Body']['stkCallback']['CallbackMetadata']
43
['Item'][1]['value'],
44
TransactionDate=data[0]['Body']['stkCallback']['CallbackMetadata']['Item']
45
[3]['value'],
46
PhoneNumber=data[0]['Body']['stkCallback']['CallbackMetadata']['Item'][4]
47
['value'])
48
db.session.add(new_user)
49
db.session.commit()```
50
This is what I had tried.
51
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:
JavaScript
1
9
1
MerchantRequestID=data['Body']['stkCallback']['MerchantRequestID']
2
CheckoutRequestID=data['Body']['stkCallback']['CheckoutRequestID']
3
ResultCode=data['Body']['stkCallback']['ResultCode']
4
ResultDesc=data['Body']['stkCallback']['ResultDesc']
5
Amount=data['Body']['stkCallback']['CallbackMetadata']['Item'][0]['Value']
6
MpesaReceiptNumber=data['Body']['stkCallback']['CallbackMetadata']['Item'][1]['Value']
7
TransactionDate=data['Body']['stkCallback']['CallbackMetadata']['Item'][3]['Value']
8
PhoneNumber=data['Body']['stkCallback']['CallbackMetadata']['Item'][4]['Value']
9