Created
August 28, 2012 05:27
-
-
Save desaiashu/3495208 to your computer and use it in GitHub Desktop.
Method to replace all instances of a string in an arbitrary object containing dictionaries, arrays, strings and numbers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def replaceStringInObject(obj, old, new): | |
if isinstance(obj, list): | |
for i in range(len(obj)): | |
if isinstance(obj[i], str) and obj[i] == old: | |
obj[i] = new | |
else: | |
replacestrinobj(obj[i], old, new) | |
elif isinstance(obj, dict): | |
for k in obj: | |
if isinstance(obj[k], str) and obj[k] == old: | |
obj[k] = new | |
else: | |
replacestrinobj(obj[k], old, new) | |
if isinstance(k, str) and k == old: | |
obj[new] = obj[k] | |
del obj[k] | |
else: | |
replacestrinobj(k, old, new) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment