I have a sample Json as mentioned below
[{
"Name": "Kim",
"Details": {
"Age": 43,
"Gender": "Male",
"Education": [{
"Primary": "Xavier",
"Percentage": 90,
"subject": [{
"sub": "Math",
"Perf": "Good"
},
{
"sub": "Sci",
"Perf": "Averge"
}, {
"sub": "Eco",
"Perf": "Good"
}
],
"Marks": [{
"Mark": 90,
"Grade": "A"
},
{
"Mark": 92,
"Grade": "S"
}, {
"Mark": 80,
"Grade": "B"
}
]
},
{
"Seconday": "Anthony",
"Percentage": 98,
"subject": [{
"sub": "Math",
"Perf": "Good"
}],
"Marks": [{
"Mark": 100,
"Grade": "S"
}]
},
{
"Bachelor": "Boston",
"Percentage": 90,
"subject": [{
"sub": "Computers",
"Perf": "Good"
}],
"Marks": [{
"Mark": 90,
"Grade": "A"
}]
},
{
"PostGrad": "Boston",
"Percentage": 90,
"subject": [{
"sub": "CNN",
"Perf": "Good"
}],
"Marks": [{
"Mark": 90,
"Grade": "A"
}]
}]
}
}]
form this I need to fetch the sub and Mark only from the entire Json.
I got the necessary output but the concern is I have utilised multiple for loops, below mentioned is my approch to fetch sub and marks,
import json
sampleJson = open('C:\\Users\\SampleJson.json')
sampleJsonData = json.loads(sampleJson.read())
resArray=[]
for i in range(len(sampleJsonData)):
for j in range(len(sampleJsonData[i]["Details"])):
for k in range(len(sampleJsonData[i]["Details"]["Education"])):
for l in range(len(sampleJsonData[i]["Details"]["Education"])):
for y in range(len(sampleJsonData[i]["Details"]["Education"][l]["subject"])):
sub = (sampleJsonData[i]["Details"]["Education"][l]["subject"][y]["sub"])
for z in range(len(sampleJsonData[i]["Details"]["Education"][l]["Marks"])):
marks = sampleJsonData[i]["Details"]["Education"][l]["Marks"][z]["Mark"]
by any means is there any possibility that I could reduce the usage of for loops to nil.
I need to use those sub and Mark values further, as a temp measure stored the values in different variables.
I'm relatively very new to python, Please help me on this. Thanks
'Math', 'Sci', 'Eco', 90, 92, 80, 'Math', 100, 'Computers', 90, 'CNN', 90
instead? \$\endgroup\$resArray
,sub
andmarks
that I don't see used. There is a lot of common (sub-)expressions ("subscripting").) \$\endgroup\$sub
andmark
further? Do you just need those values in a list, like Thingamabobs showed? Do you need separate lists of subs and marks, which your variable names suggest? Do you need only that portion of the json? Do you need a dict of{sub:mark}
for each (and if so, how should the subs from Xavier match up to the marks)? You keep overwriting your assignments tosub
andmarks
, and you never touchresArray
. \$\endgroup\$