pydantic - json 键无效 python 字段名称
pydantic - json keys are not valid python field names
我有一个 json,其键包含 python 字段名称不能包含的字符:
{
"mlflow.source.git.commit": "fbe812fe",
"other.key": "other.value"
}
如何使用pydantic
解析这样的json?我想给它一个别名和实际的键名,比如
class Tags(pydantic.BaseModel):
commit = field(key="mlflow.source.git.commit", type=str)
这可以使用 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)
我有一个 json,其键包含 python 字段名称不能包含的字符:
{
"mlflow.source.git.commit": "fbe812fe",
"other.key": "other.value"
}
如何使用pydantic
解析这样的json?我想给它一个别名和实际的键名,比如
class Tags(pydantic.BaseModel):
commit = field(key="mlflow.source.git.commit", type=str)
这可以使用 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)