Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save rafa-acioly/c2a5299d6140579e760f1639df458efb to your computer and use it in GitHub Desktop.
Save rafa-acioly/c2a5299d6140579e760f1639df458efb to your computer and use it in GitHub Desktop.
Convert all keys from json/dict from camelCase to snake_case
"""
This algorith convert all keys from json from camelCase to snake_case recursivily
"""
def _unpack(data):
if isinstance(data, dict):
return data.items()
return data
def snake_case(value):
"""
Convert camel case string to snake case
:param value: string
:return: string
"""
first_underscore = re.sub('(.)([A-Z][a-z]+)', r'\1_\2', value)
return re.sub('([a-z0-9])([A-Z])', r'\1_\2', first_underscore).lower()
def keys_to_snake_case(content):
"""
Convert all keys for given dict to snake case
:param content: dict
:return: dict
"""
return {snake_case(key): value for key, value in content.items()}
def decode_keys(data):
"""
Convert all keys for given dict/list to snake case recursively
:param data: dict
:return: dict
"""
formatted = {}
for key, value in _unpack(keys_to_snake_case(data)):
if isinstance(value, dict):
formatted[key] = decode_keys(value)
elif isinstance(value, list) and len(value) > 0:
formatted[key] = []
for _, val in enumerate(value):
formatted[key].append(decode_keys(val))
else:
formatted[key] = value
return formatted
## Usage/Example
input = {
"keyOne": "value 1",
"SecondKeyOnMyDict": [
{"subKeyOne": "sub 1"},
{"subKeyTwo": "sub 2"},
{
"subKeyThree": [
{"subSubOne": 1},
{"subSubTwo": 2}
]
},
{
"firstLevel": [
"SecondLevel": [
"ThirdLevel": [
"FourthLevel": {"soDeep": "wow"}
]
]
]
}
]
}
converted = decode_keys(input)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment