-
-
Save ggarber/1767090 to your computer and use it in GitHub Desktop.
Cast CamelCase to "underscore_case"
This file contains 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 _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