Skip to content

Instantly share code, notes, and snippets.

@jassinm
Created June 15, 2012 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jassinm/2936840 to your computer and use it in GitHub Desktop.
Save jassinm/2936840 to your computer and use it in GitHub Desktop.
Clean's up a nested structure for mongo
import re
def mongo_cleanup(item, replacement=''):
"""clean's a nested structure keys to adapt to mongodb's
legal keys
see http://www.mongodb.org/display/DOCS/Legal+Key+Names """
if hasattr(item, 'items'):
newdict = {}
for key, value in item.items():
nkey = key
if isinstance(key, basestring):
# nkey = re.sub('(^\$)|\.', replacement, key)
nkey = re.sub('\.', replacement, key)
nkey = re.sub('(^\$)', "dollar_", nkey)
nkey = nkey.replace('\x00', '')
newdict[nkey] = mongo_cleanup(value, replacement)
return newdict
elif isinstance(item, list):
return [mongo_cleanup(val, replacement) for val in item]
else:
return item
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment