你好,我正在阅读具有以下格式的JSON:
{
"1": {"id":1, "type": "a"},
2: {"id":2, "type": "b"},
"3": {"id":3, "type": "c"},
"5": {"id":4, "type": "d"}
}正如你所看到的,这些键是数字,但不是连续的。
所以我有下面的BaseModel到嵌套的dict
@validate_arguments
class ObjI(BaseModel):
id: int
type: str问题是如何验证dict中的所有项都是ObjI,而无需使用:
objIs = json.load(open(path))
assert type(objIs) == dict
for objI in objIs.values():
assert type(objI) == dict
ObjI(**pair)我试过:
@validate_arguments
class ObjIs(BaseModel):
ObjIs: Dict[Union[str, int], ObjI]编辑
验证前一项的错误是:
in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class这个是可能的吗?
谢谢
发布于 2022-04-11 18:13:18
您可以将模型定义更改为使用https://pydantic-docs.helpmanual.io/usage/models/#custom-root-types (不需要validate_arguments装饰器):
from pydantic import BaseModel
from typing import Dict
class ObjI(BaseModel):
id: int
type: str
class ObjIs(BaseModel):
__root__: dict[int, ObjI]现在可以使用JSON数据初始化模型,例如:
import json
with open("/path/to/data") as file:
data = json.load(file)
objis = ObjIs.parse_obj(data)如果data包含无效类型(或缺少字段),prase_obj()将引发ValidationError。例如,如果data看起来是这样的:
data = {
"1": {"id": "x", "type": "a"},
# ^
# wrong type
2: {"id": 2, "type": "b"},
"3": {"id": 3, "type": "c"},
"4": {"id": 4, "type": "d"},
}
objs = ObjIs.parse_obj(data)这将导致:
pydantic.error_wrappers.ValidationError: 1 validation error for ObjIs
__root__ -> 1 -> id
value is not a valid integer (type=type_error.integer)这告诉我们,具有键id的对象的1类型无效。
(您可以像处理Python中的任何其他异常一样捕获和处理ValidationError。)
( pydantic 文档还建议在模型上实现自定义__iter__和__getitem__方法,如果您想直接访问__root__字段中的项。)
https://stackoverflow.com/questions/71824924
复制相似问题