When implementing using an external API, the REST API return value may be CamelCase json. For example, it happens frequently when operating AWS with boto3
in Python.
That would be a bit of a problem considering the Python coding conventions, but pydantic
uses the ʻalias_generator` function. (: //pydantic-docs.helpmanual.io/usage/model_config/#alias-generator) and you can easily cast to a snake_case keyed type.
In the documentation, I made my own function called to_camel
, but I have an external library ʻinflection` for use in various classes in AWS operations. I am using.
from pydantic import BaseModel
from inflection import camelize
class Voice(BaseModel):
name: str
language_code: str
class Config:
alias_generator = camelize
voice = Voice(**{'Name': 'Filiz', 'LanguageCode': 'tr-TR'})
print(voice.language_code)
#> tr-TR
print(voice.dict(by_alias=True))
#> {'Name': 'Filiz', 'LanguageCode': 'tr-TR'}
Recommended Posts