how to validate keys with whitespaces in pydantic
Question:
I have a json key with whitespace in it:
My_dict = {"my key": 1}
I want to create a Model
to model it:
from pydantic import BaseModel
class MyModel(BaseModel):
mykey: int
# my key isn't a legit variable name
# my_key is, but like mykey - it doesn't catch the correct key from the json
MyModel(**my_dict)
This doesn’t work.
I tried playing with the BaseModel.Config
, but didn’t get anywhere. Didn’t see anything on the docs as well.
Is this possible?
I can use a workaround: Go over the json
, replace all key’s whitespaces into underscores, and then use pydantic
but I would love to not use this…
Answers:
Yes, it’s possible by using Field’s aliases:
from pydantic import BaseModel, Field
class MyModel(BaseModel):
mykey: int = Field(alias='my key')
class Config:
allow_population_by_field_name = True
print(MyModel(**{"my key": 1}))
print(MyModel(**{'mykey': 1}))
I have a json key with whitespace in it:
My_dict = {"my key": 1}
I want to create a Model
to model it:
from pydantic import BaseModel
class MyModel(BaseModel):
mykey: int
# my key isn't a legit variable name
# my_key is, but like mykey - it doesn't catch the correct key from the json
MyModel(**my_dict)
This doesn’t work.
I tried playing with the BaseModel.Config
, but didn’t get anywhere. Didn’t see anything on the docs as well.
Is this possible?
I can use a workaround: Go over the json
, replace all key’s whitespaces into underscores, and then use pydantic
but I would love to not use this…
Yes, it’s possible by using Field’s aliases:
from pydantic import BaseModel, Field
class MyModel(BaseModel):
mykey: int = Field(alias='my key')
class Config:
allow_population_by_field_name = True
print(MyModel(**{"my key": 1}))
print(MyModel(**{'mykey': 1}))