Camel Converter

5.1.0 · active · verified Sat Apr 11

Camel Converter is a Python library designed to effortlessly convert strings and dictionary keys between camel case, snake case, and pascal case. It's particularly useful for handling JSON data where keys are often in camelCase, facilitating seamless integration with Python's snake_case conventions. The library also provides decorators for automatic dictionary key conversion in function returns and offers integration with Pydantic models. The current version is 5.1.0.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates basic string and dictionary key conversion using `to_snake`, `to_camel`, `dict_to_snake`, and decorator-based conversion with `dict_to_camel`. It also includes an example of using `CamelBase` for Pydantic models, which automatically handles camelCase to snake_case mapping for model instantiation.

from camel_converter import to_snake, to_camel, dict_to_snake
from camel_converter.decorators import dict_to_camel
from pydantic import BaseModel # For CamelBase example

# String conversion
snake_case_string = to_snake('myCamelCaseString')
print(f"'myCamelCaseString' to snake_case: {snake_case_string}")

camel_case_string = to_camel('my_snake_case_string')
print(f"'my_snake_case_string' to camelCase: {camel_case_string}")

# Dictionary key conversion
camel_dict = {'firstName': 'John', 'lastName': 'Doe', 'dateOfBirth': '1990-01-01'}
snake_dict = dict_to_snake(camel_dict)
print(f"CamelCase dict to snake_case: {snake_dict}")

# Decorator usage
@dict_to_camel
def get_data_from_db() -> dict:
    # Simulate fetching data with snake_case keys
    return {'user_id': 123, 'user_name': 'test_user'}

api_response = get_data_from_db()
print(f"Decorated function output (snake_case to camelCase): {api_response}")

# Pydantic integration (requires 'pydantic' to be installed)
try:
    from camel_converter.pydantic_base import CamelBase

    class User(CamelBase):
        first_name: str
        last_name: str

    user_data_camel = {'firstName': 'Jane', 'lastName': 'Smith'}
    user_obj = User(**user_data_camel)
    print(f"Pydantic CamelBase model from camelCase input: {user_obj.first_name} {user_obj.last_name}")
except ImportError:
    print("Pydantic not installed. Skipping CamelBase example.")

view raw JSON →