python - 使用有用的错误消息有条件地要求 jsonSchema 枚举属性
问题描述
我可能做错了,因为错误消息没有帮助-即使这“有效”
我有一个可以是 aaa 或 bbb 的枚举 (field1)
如果它是 aaa,那么 field2 必须是必需的。如果不是 aaa,则 field2 可以是可选的
我现在有这个
"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'}
推荐阅读
- amazon-web-services - AWS Cloudformation nested intrinsic function not evaluating
- c# - Update the video source device list
- elixir - 如何使用 Enum.map 以与 Elixir 中的其他元素略有不同的方式修改集合的第一个元素?
- javascript - javascript moment.js script not working quite right
- python - python tkinter 条目小部件动态名称
- python - GroupBy - Python
- amazon-dynamodb-dax - UnboundLocalError: local variable 'key_schema' referenced before assignment
- java - Spring: Implement a share-via-link feature for web application
- java - 如何在Java中实现注解为@Retention(RetentionPolicy.SOURCE)的注解
- c# - NUnit - 没有找到合适的构造函数