Skip to content

Instantly share code, notes, and snippets.

@desaiashu
Created August 28, 2012 05:27
Show Gist options
  • Save desaiashu/3495208 to your computer and use it in GitHub Desktop.
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
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