0

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'}}} 
10
  • To clarify: you already have a dictionary, and you want to print all the values, including values in nested dictionaries, but not the keys? What is the expected output for your example? Commented Feb 8, 2016 at 6:18
  • I need to iterate through each key and value, replace all the values in the json with some other value. Commented Feb 8, 2016 at 6:22
  • You have to traverse over each key and value of your dict. Also have to check, if value is again dict, then do same. Commented Feb 8, 2016 at 6:22
  • 1
    That is different to what you asked for in your question... Commented Feb 8, 2016 at 6:23
  • 1
    One last try before I decide this is a waste of time: show the expected result. Commented Feb 8, 2016 at 6:24

1 Answer 1

1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

This works for the value but I would need keys as well as I would need to set that value with a new value

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.