Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

parsing json conditionally using python

{
"info":[
{
    "subinfo":{
        "name":"ABC",
        "age":23,
        "sex":"M",
        "addr":"xyz",
        "regDt":"01-Jan-2021"
    },
    "city":"NY"
    "eduInfo":{
        "deg":"BA"
        "master":"PhD"
    },
    "sports":{
        "indoor":"poker",
        "outdoor":"hockey"
    }
},
"info":[
{
    "subinfo":{
        "name":"PQR",
        "age":23,
        "sex":"F",
        "addr":"def",
        "regDt":"01-Jan-2021"
    },
    "city":"NY"
    "eduInfo":{
        "deg":"BA"
        "master":"NA"
    },
    "sports":{
        "indoor":"poker",
        "outdoor":"hockey"
    }
}
}

The above data is a simple example of what kind of data I am working with. There are
such hundreds of info's basically of Males and Females. I need two separate lists for both, Males and Females. So, to extract the data of Males i.e; sex="M", I am using this condition

data = json.loads(data)

for m in data['info'] :
    if m['subinfo']['sex'] == "M" :
            mList = m

print(mList)

#and for Females list

for f in data['info'] :
    if f['subinfo']['sex'] == "F" :
            fList = f

print(fList)

I am expecting more than 1 record for each, Males and Females, but the actual result is
only one for each. What’s wrong with this code?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You set the variable to the object each time. Because of this, the variable will be whatever the last matching object was. Instead, set the variable to an empty list and then append the objects to that list.

mList = []
for m in data['info']:
    if m['subinfo']['sex'] == 'M':
         mList.append(m)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading