-
-
Save rafeca/1767403 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((_camel_to_underscore_case(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), obj) | |
else: | |
return obj | |
if __name__ == "__main__": | |
import unittest | |
class TestCamelToUnderscore(unittest.TestCase): | |
def setUp(self): | |
self.input = {'object': [ | |
{"IsCustomer": True, "OBID": 12345}, | |
{"isCustomer": True, "obid": 12345}, | |
{"is_customer": True, "obid": 12345}, | |
{"isCustomer": True, "Obid": 12345}, | |
{"obj": {"isCustomer": True, "Obid": 12345}} | |
]} | |
def test_conversion(self): | |
output = camel_to_underscore_case(self.input) | |
camelcased = {"is_customer": True, "obid": 12345} | |
expected = {'object': [camelcased] * 4 + [{"obj": camelcased}]} | |
self.assertDictEqual(expected, output) | |
unittest.main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment