'pydantic - json keys are not valid python field names
I have a json with keys containing characters that a python field name can't contain:
{
"mlflow.source.git.commit": "fbe812fe",
"other.key": "other.value"
}
How to use pydantic to parse such a json? I'd like to give it an alias and actual key name, like
class Tags(pydantic.BaseModel):
commit = field(key="mlflow.source.git.commit", type=str)
Solution 1:[1]
This is possible using pydantic.Field(alias="..."):
import pydantic
class Tags(pydantic.BaseModel):
commit : str = pydantic.Field(alias="mlflow.source.git.commit")
data = {
"mlflow.source.git.commit": "fbe812fe",
"other.key": "other.value"
}
t = Tags(**data)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | ikamen |
