简体   繁体   中英

How to extract values of specific key inside list of JSON dictionaries

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.

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'] .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM