在pydantic.validators.find_validators typeError:issubclass()arg 1必须是类
您好,我正在阅读带有以下格式的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> 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
这可能吗?
谢谢
Hello I am reading a JSON with the following format:
{
"1": {"id":1, "type": "a"},
2: {"id":2, "type": "b"},
"3": {"id":3, "type": "c"},
"5": {"id":4, "type": "d"}
}
As you can see the keys are numbers but are not consecutives.
So I have the following BaseModel
to the nested dict
:
@validate_arguments
class ObjI(BaseModel):
id: int
type: str
The question is how can I validate that all items in the dict
are ObjI
without use of:
objIs = json.load(open(path))
assert type(objIs) == dict
for objI in objIs.values():
assert type(objI) == dict
ObjI(**pair)
I tried with:
@validate_arguments
class ObjIs(BaseModel):
ObjIs: Dict[Union[str, int], ObjI]
EDIT
The error validating the previous is:
in pydantic.validators.find_validators TypeError: issubclass() arg 1 must be a class
Is this possible?
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以更改模型定义以使用自定义根类型(不需要
validate_arguments
装饰器):现在可以使用 JSON 数据初始化模型,例如:
如果
data
包含无效的内容类型(或缺少字段),prase_obj()
将引发ValidationError
。例如,如果
data
看起来像这样:它将导致:
这告诉我们具有键
1
的对象的id
具有无效的类型。(您可以像 Python 中的任何其他异常一样捕获并处理
ValidationError
。)(pydantic docs 还建议在模型上实现自定义
__iter__
和__getitem__
方法(如果您想访问中的项目)直接输入__root__
字段。)You could change your model definitions to use a custom root type (no need for the
validate_arguments
decorators):The model can now be initialised with the JSON data, e.g. like this:
If
data
contains invalid types (or has missing fields),prase_obj()
will raise aValidationError
.For examples, if
data
looked like this:it would result in:
which tells us that the
id
of the object with key1
has an invalid type.(You can catch and handle a
ValidationError
like any other exception in Python.)(The pydantic docs also recommend to implement custom
__iter__
and__getitem__
methods on the model if you want to access the items in the__root__
field directly.)