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')
My_dict = {"my key": 1}
print(MyModel(**My_dict))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.