Created
June 15, 2012 14:53
-
-
Save jassinm/2936840 to your computer and use it in GitHub Desktop.
Clean's up a nested structure for mongo
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
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