[PYTHON] Cast json with key CamelCase to snake_case class in pydantic

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'}

reference

Recommended Posts

Cast json with key CamelCase to snake_case class in pydantic
Convert / return class object to JSON format in Python
How to cast with Theano
How to not escape Japanese when dealing with json in python
Log in to Raspberry PI with ssh without password (key authentication)
How to deal with garbled characters in json of Django REST Framework
How to access data with object ['key'] for your own Python class
[Introduction to Python] How to use class in Python?
Convert Excel data to JSON with python
How to work with BigQuery in Python
Playing card class in Python (with comparison)
Dictionary key error → Resolve with key in dicionary
How to use __slots__ in Python class
Convert array (struct) to json with golang
To work with timestamp stations in Python
I tried to create a class that can easily serialize Json in Python
[Python] Created a class to play sin waves in the background with pyaudio