Skip to content
Advertisement

How to inflect from snake case to camel case post the pydantic schema validations

I can able to find a way to convert camelcase type based request body to snake case one by using Alias Generator, But for my response, I again want to inflect snake case type to camel case type post to the schema validation. Is there any way I can achieve this?

Example: I do have a python dict as below,

{
 "title_name": "search001",
 "status_type": "New" 
}

And post to the pydantic schema validation my dict should convert snake case type to camel case as below,

{
 "titleName": "search001",
 "statusType": "New" 
}

How can I define a pydantic schema to achieve the above problem?

Thanks in advance.

Advertisement

Answer

You can use Alias Generator

from pydantic import BaseModel


def to_snake_case(string: str) -> str:
    return ''.join(['_' + i.lower() if i.isupper() else i for i in string]).lstrip('_')


class MyModel(BaseModel):
    titleName: str
    statusType: str

    class Config:
        alias_generator = to_snake_case


data = {
    "title_name": "search001",
    "status_type": "New"
}
print(MyModel(**data).dict()) # {'titleName': 'search001', 'statusType': 'New'}

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement