Skip to content Skip to sidebar Skip to footer

How To Extract The Attributes From A Node In A Json Dictionary?

I have a dictionary which contains the following json elements. myjsonDictionary = \ { 'Teams': { 'TeamA': { '@oid': '123.0.0.1', 'dataRequestList': { 's

Solution 1:

With recursive traversal for specific keys:

def get_team_idlvel_oid_pair(d, search_key):
    for k, v in d.items():
        if k.startswith('Team'):
            if k == search_key:
                return '{}{}.{}'.format(d['@oid'] + '.' if '@oid' in d else '',
                                        v['@oid'], v['dataRequestList']['state']['@oid'])
            elif any(k.startswith('Team') for k_ in v):
                return get_team_idlvel_oid_pair(v, search_key)


print(get_team_idlvel_oid_pair(myjsonDictionary['Teams'], 'TeamA'))
print(get_team_idlvel_oid_pair(myjsonDictionary['Teams'], 'TeamSub'))

Sample output:

123.0.0.1.2
123.0.0.1.3.2

Post a Comment for "How To Extract The Attributes From A Node In A Json Dictionary?"