简体   繁体   中英

Iterating nested json in python

I have JSON in this format. How can I print each value and go inside the objects. Also, the json can vary and also the name, so I need a generic solution.

output = {'name':'StackOverflow',
       'competitors':[{   'competitor':'bing',
                          'link':'bing.com'},
                      {   'competitor':'google',
                          'link':'google.com'}],
       'acquisition': {'acquired_day': 16,
                       'acquired_month': 12,
                       'acquired_year': 2013,
                       'acquiring_company': {'name': 'Viggle',
                                             'permalink': 'viggle'}}} 

You can use isinstance to check if something is a dict or a list. Something like this may work, but I haven't checked it.

output = {'name': 'StackOverflow',
      'competitors': [{'competitor': 'bing',
                       'link': 'bing.com'},
                      {'competitor': 'google',
                       'link': 'google.com'}],
      'acquisition': {'acquired_day': 16,
                      'acquired_month': 12,
                      'acquired_year': 2013,
                      'acquiring_company': {'name': 'Viggle',
                                            'permalink': 'viggle'}}}


def traverse(obj):
    if isinstance(obj, dict):
        for key, value in obj.iteritems():
            print('dict_key', key)
            traverse(value)
    elif isinstance(obj, list):
        for value in obj:
            traverse(value)
    else:
        print('value', obj)


traverse(output)

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