Home > database >  parsing json conditionally using python
parsing json conditionally using python

Time:03-21

{
  "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"
      }
    },
    {
      "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?

CodePudding user response:

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)
  • Related