views:

49

answers:

2

Is there some kind of enumeration library or method I should use or should I write from scratch with recursion?

I'm parsing a JSON tree into an object tree as it happens, and I'd like to replace some nodes with other kinds of objects.

E.g:

db = {'bigBang' :
          {'stars':
               {'planets': {}, 'is_list':true
               }
           }
     }
db.deepReplace( 'is_list', ['earth', 'mars'] )
>> db is now: 
>> {'bigBang' :
>>        {'stars':
>>             {'planets':
>>                 {
>>                     ['earth', 'mars']
>>                 }
>>             }
>>         }
>> }
+1  A: 

It's hard to tell exactly what you're trying to accomplish; I guess you want deepReplace to replace any node named "planets" with a map containing "earth" and "mars"?

It's pretty easy to write that function, especially if you know the tree will contain dicts. If not, you need to test the type (or catch the errors) when you try and recurse.

def deep_replace(d, key, replacement):
    for k, value in d.items():
        if k == key:
            d[k] = replacement
        else:
            deep_replace(value, key, replacement)
Chris B.
+1  A: 

If you know there's only one node to replace:

def deepReplace(d, key, value):
    if isinstance(d, dict):
        if key in d:
            d[key] = value
            return True
        else:
            for k,v in d.iteritems():
                if deepReplace(v, key, value):
                    return True
    return False

Otherwise:

def deepReplace(d, key, value):
    if isinstance(d, dict):
        if key in d:
            d[key] = value
        else:
            for k,v in d.iteritems():
                deepReplace(v, key, value):
Marcelo Cantos