Home > Net >  How to extract values of specific key inside list of JSON dictionaries
How to extract values of specific key inside list of JSON dictionaries

Time:01-25

Hi I have a json file "groups" with below format and I need to list all the values of key "groupId".

{
    'accountId': '1234',
    'accountName': 'ABCD',
    'groups': {
        'items': [{
            'groupName': 'groupA',
            'groupId': 'grp_111',
            'parentGroupId': 'grp_567',
            'contractIds': ['ctr_567']
        }, {
            'groupName': 'groupB',
            'groupId': 'grp_222',
            'parentGroupId': 'grp_567',
            'contractIds': ['ctr_567']
        }

I tried below code

result = session.get(urljoin(baseurl, path), headers=headers, verify=False)
groups = result.json()

print (groups['groups'])
for i in groups['items']:
    for groupId in i:
        print ('groupId')

but getting KeyError: 'items'

I'm expecting to see a list of all the groupIds or it could be in key-value format.

CodePudding user response:

You're getting a KeyError because your top-level dictionary does not have an items key. It has a groups key, which in turn has an items key:

for i in groups['groups']['items']:

Within that loop, i will be a dictionary so you don't need another for loop; you just need:

for i in groups['groups']['items']:
    print(i['groupId'])

If you just want a list of group ids, you could write:

groupids = [group['groupId'] for group in groups['groups']['items']]

This would result in groupids containing the value ['grp_111', 'grp_222'].

  • Related