i have json response like this :
r = {
"ID": "0001",
"ST": "87549937737",
"DT": "22062022",
"DATA": {
"0": {
"PC": "100",
"NM": "ALEX",
"AMOUNT": "210,912",
"ACT": "123123456"
},
"1": {
"PC": "100",
"NM": "MARCO",
"AMOUNT": "500,200",
"ACT": "123555456"
},
"2": {
"PC": "100",
"NM": "TIFFANY",
"AMOUNT": "712,111",
"ACT": "123666981"
}
},
"RCMSG": {
"0": {
"SEVERITY": "00"
}
},
"RC": "0000"
}
and i want to parse every loop items in DATA, and my scripts are like this :
for items in r['DATA']:
jdata = {'PRODUCTCODE': items['PC'], 'NAME': items['NM'], 'AMOUNTBALANCE': items['AMOUNT'], 'ACCOUNT': items['ACT']}
return jsonify({'status':'success', 'code':'00', 'data': jdata})
but the response is only parsed '0' in 'DATA, how do i loop every items inside 'DATA' ?
{
"PRODUCTCODE": "100",
"NAME": "ALEX",
"AMOUNTBALANCE": "210,912",
"ACCOUNT": "123123456"
}
CodePudding user response:
In your code, there is a return
statement inside the for loop, so it will never traverse all elements in JSON
data because it will end its execution at the first item. So, you need to traverse all elements accessing them from the original JSON
response:
r = {
"ID": "0001",
"ST": "87549937737",
"DT": "22062022",
"DATA": {
"0": {
"PC": "100",
"NM": "ALEX",
"AMOUNT": "210,912",
"ACT": "123123456"
},
"1": {
"PC": "100",
"NM": "MARCO",
"AMOUNT": "500,200",
"ACT": "123555456"
},
"2": {
"PC": "100",
"NM": "TIFFANY",
"AMOUNT": "712,111",
"ACT": "123666981"
}
},
"RCMSG": {
"0": {
"SEVERITY": "00"
}
},
"RC": "0000"
}
d = []
for i in r['DATA']:
d.append(r['DATA'][i])
print(d)
Output:
[{'PC': '100', 'NM': 'ALEX', 'AMOUNT': '210,912', 'ACT': '123123456'}, {'PC': '100', 'NM': 'MARCO', 'AMOUNT': '500,200', 'ACT': '123555456'}, {'PC': '100', 'NM': 'TIFFANY', 'AMOUNT': '712,111', 'ACT': '123666981'}]
CodePudding user response:
results = []
for k, v in r['DATA'].items():
item = {
"PRODUCTCODE": v["PC"],
"NAME": v["NM"],
"AMOUNTBALANCE": v["AMOUNT"],
"ACCOUNT": v["ACT"],
}
results.append(item)