Skip to content

Instantly share code, notes, and snippets.

@jackylamhk
Last active November 15, 2023 17:37
Show Gist options
  • Save jackylamhk/0231771bba097c5b6da37bc7549695d1 to your computer and use it in GitHub Desktop.
Save jackylamhk/0231771bba097c5b6da37bc7549695d1 to your computer and use it in GitHub Desktop.
Converting between camelCase and snake_case. Useful for communicating with APIs written in other languages.
"""
This module is created as Keycloak is written in Java, and I am not
succubming to Java or JavaScript's naming convention. #fuckthefrontend -J
Inspired by @sanders41/camel-converter
"""
def to_snake(string: str):
"""
Converts strings in camelCase or PascalCase to snake_case.
"""
new_string = ""
for index, char in enumerate(string):
if char.isupper() and index >= 0 and new_string[index - 1].islower():
new_string += "_"
new_string += char
return new_string.lower()
def dict_to_snake(obj: dict | list[dict]):
"""
Converts all keys in an object to snake_case.
"""
if isinstance(obj, dict):
return {to_snake(k): dict_to_snake(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [dict_to_snake(e) for e in obj]
else:
return obj
def to_camel(string: str):
"""Converts strings in snake_case to camelCase."""
words = string.split("_")
return words[0] + "".join(word.title() for word in words[1:])
def dict_to_camel(obj: dict | list[dict]):
"""
Converts all keys in a dictionary from snake_case to camelCase.
"""
if isinstance(obj, dict):
return {to_camel(k): dict_to_camel(v) for k, v in obj.items()}
elif isinstance(obj, list):
return [dict_to_camel(e) for e in obj]
else:
return obj
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment