使jsonSchema枚举属性是有条件要求的,并带有有用的错误消息



我可能做错了,因为错误消息没有帮助-即使这"有效">

我有一个枚举(字段1(,可以是aaa或bbb

如果它是aaa,那么字段2必须是必需的。如果不是aaa,则字段2可以是可选的

我现在有这个

"anyOf": [
{
"properties": {
"field1": {
"const": "aaa"
}
},
"required": [
"field2"
]
},
{
"properties": {
"field1": {
"const": "bbb"
}
}
}
]

但如果field1=aaa且未指定field2,则会出现以下错误:

E           jsonschema.exceptions.ValidationError: 'bbb' was expected
E           
E           Failed validating 'const' in schema[1]['properties']['field1']:
E               {'const': 'bbb'}
E           
E           On instance['httpMethod']:
E               'aaa'

我期待一个更像"field2" expected because schema[1]['properties']['field1'] == bbb的错误

我用错这个了吗?

如果您使用>=draft-07,我想if-then(-else)将为您提供最佳错误。

from jsonschema import Draft7Validator
schema = {
"type": "object",
"properties": {
"field1": {
"enum": [
"aaa",
"bbb"
]
},
"field2": {
"type": "string"
}
},
"if": {
"properties": { "field1": { "const": "aaa" } }
},
"then": {
"required": [ "field2" ]
}
}
obj = {
"field1": "aaa",
}
Draft7Validator(schema).validate(obj)

它将生成错误:

Traceback (most recent call last):
File "error.py", line 28, in <module>
Draft7Validator(schema).validate(obj)
File "(...)/jsonschema/validators.py", line 353, in validate
raise error
jsonschema.exceptions.ValidationError: 'field2' is a required property
Failed validating 'required' in schema['if']['then']:
{'required': ['field2']}
On instance:
{'field1': 'aaa'}

最新更新