1

I've got a number of JSON files of different structures that all have a number of levels of "nesting". I need to examine certain keys that can appear anywhere in the object and update these.

Am struggling to handle the "nested" elements

I've got some code that have cobbled together from much Googling (am new to Python) and have tried both instance(value,dict) and type(value) is dict

However in no cases has the log showed "iterating deeper".

def iterate(dictionary):
    for key, value in dictionary.items():
        print('key {} -> value {}'.format(key, value))
        #if logic to update specific values
            print('Dict new value {}'.format(value))
        if isinstance(value, dict):
        #if type(value) is dict:
            print('Iterating deeper. Key {}'.format(key))
            dictionary[key] = iterate(value)
    return(dictionary)

Simple JSON example:

myObj = {
  "name":"John",
  "age":30,
  "cars": {
    "car1":"Ford",
    "car2":"BMW",
    "car3":"Fiat"
  }
 }

I'd expect to see "Iterating deeper. Key cars" printed out

2
  • elif without if? Commented Sep 1, 2019 at 8:25
  • yes- sorry- maybe not clear there- have removed the "if" logic for the specific use case (is commented) Commented Sep 1, 2019 at 8:28

1 Answer 1

2

To update:

def iterjson(data):
    for key, value in data.items():
        if (update_condition):
            data[key] = new_value

        print('key {} -> value {}'.format(key, value))
        if isinstance(value, dict):
            print('Iterating deeper. Key {}'.format(key))
            yield from iterjson(value)
        else:
            yield value

To iterate without updating:

def iterjson(data):
    for key, value in data.items():
        print('key {} -> value {}'.format(key, value))
        if isinstance(value, dict):
            print('Iterating deeper. Key {}'.format(key))
            yield from iterjson(value)
        else:
            yield value

If you want to iterate with list as well:

def iterjson(data):
    for key, value in data.items():
        print('key {} -> value {}'.format(key, value))
        if isinstance(value, dict):
            print('Iterating deeper. Key {}'.format(key))
            yield from iterjson(value)
        elif isinstance(value, list):
            for i in value:
                yield i
        else:
            yield value
Sign up to request clarification or add additional context in comments.

Comments

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.