Skip to content

Instantly share code, notes, and snippets.

@juandebravo
Created February 7, 2012 23:35
Show Gist options
  • Save juandebravo/1762991 to your computer and use it in GitHub Desktop.
Save juandebravo/1762991 to your computer and use it in GitHub Desktop.
Cast CamelCase to "underscore_case"
import re
import json
def add_underscore(letter):
return "_"+letter.group(0).lower()
def to_lower(letter):
return letter.group(0).lower()
def cast_to_underscore_case(value):
if isinstance(value, str):
return re.sub(r'([A-Z])', add_underscore, value)
elif isinstance(value, dict):
_values = {}
for (k, v) in value.items():
_k = re.sub(r'([A-Z]){2,}', to_lower, k)
_k = re.sub(r'\A([A-Z])', to_lower, _k)
_k = re.sub(r'(?<=.)([A-Z])[a-z]', add_underscore, _k)
_k = re.sub(r'(?<=.)([A-Z]$)', add_underscore, _k)
_values[_k] = v
return _values
else:
raise TypeError("Unexpected type {}".format(type(value)))
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}
]
for val in values:
print "-------------\n"
print val
print "->"
print cast_to_underscore_case(val)
@juandebravo
Copy link
Author

Result:

-------------

{'IsCustomer': True, 'OBID': 12345}
->
{'is_customer': True, 'obid': 12345}
-------------

{'isCustomer': True, 'obid': 12345}
->
{'is_customer': True, 'obid': 12345}
-------------

{'iscustomer': True, 'obid': 12345}
->
{'iscustomer': True, 'obid': 12345}
-------------

{'is_customer': True, 'obid': 12345}
->
{'is_customer': True, 'obid': 12345}
-------------

{'isCustomer': True, 'oBiD': 12345}
->
{'is_customer': True, 'o_bi_d': 12345}
-------------

{'isCustomer': True, 'Obid': 12345}
->
{'is_customer': True, 'obid': 12345}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment