Skip to content

Instantly share code, notes, and snippets.

@ggarber
Forked from juandebravo/main_re.py
Created February 8, 2012 09:23
Show Gist options
  • Save ggarber/1767090 to your computer and use it in GitHub Desktop.
Save ggarber/1767090 to your computer and use it in GitHub Desktop.
Cast CamelCase to "underscore_case"
import re
def _camel_to_underscore_case(name):
"""
Translate 'CamelCaseNames' to 'camel_case_names'.
"""
camelcase_boundry = '((?<=[a-z])[A-Z])'
return re.sub(camelcase_boundry, '_\\1', name).lower()
def camel_to_underscore_case(obj, deep=True):
if isinstance(obj, dict):
return dict((_camelcase_to_spaces(k),
camel_to_underscore_case(v, deep) if deep else v)
for k,v in obj.iteritems())
elif deep and isinstance(obj, list):
return map(lambda x: camel_to_underscore_case(x, deep))
else:
return obj
if __name__ == "__main__":
values = [
{"IsCustomer": True, "OBID": 12345},
{"isCustomer": True, "obid": 12345},
{"iscustomer": True, "obid": 12345},
{"is_customer": True, "obid": 12345},
{"isCustomer": True, "oBiD": 12345},
{"isCustomer": True, "Obid": 12345},
{"obj": {"isCustomer": True, "Obid": 12345}}
]
for val in values:
print "-------------"
print val
print "->"
print camel_to_underscore_case(val)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment