Skip to content
Advertisement

Access attributes in JSON file with python and filter items which attribute matches to specific value

I have JSON file (list.json) as an input:

"Module1": {
  "Description": "",
  "Layer": "1",
  },
  "Vendor": ""
  },
"Module2": {
  "Description": "",
  "Layer": "2",
  },
  "Vendor": ""
  },

"Module3": {
  "Description": "",
  "Layer": "3",
  },
  "Vendor": ""
  },

"Module1": 4
  "Description": "",
  "Layer": "4",
  },
  "Vendor": ""
  },

I am trying to extract all modules (their names) if “Vendor” matches to some criteria, in this case all of the modules with “Vendor”: “comp” should be printed (Module2, Module3).

My code is: import json

list_components = []

with open (/list.json) as f:
    swc_list = json.load(f)

for i in swc_list:
   if i['Vendor'] == 'comp':
    list_components.append(i)

print (list_components)

When I run this code, I keep getting: string indices must be integers on line if i['Vendor'] == 'comp':

What would be the best approach to do this?

Advertisement

Answer

You are only missing the fact that your dictionnary of module is a nested one. Each module description is a dictionnary itself.

To iterate through your modules (the keys of your dictionnary) you have to use the .keys() or the .items() method. You can then access every inner dictionnaries.

list_components = []
#iterate through the keys of swc_list
for k in swc_list.keys():
  if swc_list[k]['Vendor'] == 'comp':
    list_components.append(k)

print (list_components)

EDIT:

If you want to take the attributes of your different modules you juste have to access them using their key in the inner dictionary. By specifying which attribute of your dictionary you want you can access its value.

swc_list['Module1'] will give you the entire description dictionnary of the first module

{
        "Description": "",
        "Layer": "1",
        "Vendor": "",
      }

swc_list['Module1']['Layer'] will give you only the value associated with the Layer parameter of th first module

list_components = []

for k in swc_list.keys():
  if swc_list[k]['Vendor'] == 'comp':
    #instead of keeping only the main key (Module) you can append a tuple containing the Module and its attribute Layer 
    list_components.append((k,swc_list[k]['Layer']))

print (list_components)
>>>[('Module2', '1'), ('Module3', '1')]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement