[英]jsonschema: Abstract Data Type and correct error message
我正在使用这样的jsonschema
Python 库:
import jsonschema
schema = {
"type": "object",
"oneOf": [
{
"type": "object",
"additionalProperties": False,
"required": ["key"],
"properties": {"key": {"enum": ["foo"], "type": "string"}},
},
{
"type": "object",
"additionalProperties": False,
"required": ["key", "baritem"],
"properties": {
"key": {"enum": ["bar"], "type": "string"},
"baritem": {"type": "string"},
},
},
],
}
我可以验证正确的数据:
jsonschema.validate({"key": "bar", "baritem": "ok"}, schema)
但是如果缺少一个属性,如果失败(如预期的那样),但有一个奇怪的错误消息:
jsonschema.validate({"key": "bar"}, schema)
Traceback (most recent call last):
File "valid.py", line 29, in <module>
jsonschema.validate({"key": "bar"}, schema)
File "/home/david/.pyenv/versions/3.7.11/lib/python3.7/site-packages/jsonschema/validators.py", line 934, in validate
raise error
jsonschema.exceptions.ValidationError: 'bar' is not one of ['foo']
Failed validating 'enum' in schema[0]['properties']['key']:
{'enum': ['foo'], 'type': 'string'}
On instance['key']:
'bar'
我的第一个问题是:定义JSON
模式是否正确,尤其是使用enum
定义key
的部分?
我的第二个问题是:有没有办法用jsonschema
正确定义这样的抽象数据类型,即告诉jsonschema
根据key
属性选择object
中列出的oneOf
,并基于此 rest?
现在,我的解决方案是选择自己使用的特定模式:
import jsonschema
from jsonschema.exceptions import ValidationError
schema_foo = {
"type": "object",
"additionalProperties": False,
"required": ["key"],
"properties": {"key": {"enum": ["foo"], "type": "string"}},
}
schema_bar = {
"type": "object",
"additionalProperties": False,
"required": ["key", "baritem"],
"properties": {
"key": {"enum": ["bar"], "type": "string"},
"baritem": {"type": "string"},
},
}
schema = {
"type": "object",
"oneOf": [
schema_foo,
schema_bar,
],
}
schema_by_key = {"foo": schema_foo, "bar": schema_bar}
data = {"key": "bar"}
try:
key = data["key"]
except KeyError:
raise ValidationError("key is missing")
try:
specific_schema = schema_by_key[key]
except KeyError:
raise ValidationError("key is invalid")
jsonschema.validate(data, specific_schema)
所以错误被正确报告:
Traceback (most recent call last):
File "valid.py", line 43, in <module>
jsonschema.validate(data, specific_schema)
File "/home/david/.pyenv/versions/3.7.11/lib/python3.7/site-packages/jsonschema/validators.py", line 934, in validate
raise error
jsonschema.exceptions.ValidationError: 'baritem' is a required property
Failed validating 'required' in schema:
{'additionalProperties': False,
'properties': {'baritem': {'type': 'string'},
'key': {'enum': ['bar'], 'type': 'string'}},
'required': ['key', 'baritem'],
'type': 'object'}
On instance:
{'key': 'bar'}
您可以根据if
/ then
/ else
以及dependentSchemas
的其他属性的值选择要应用的子模式: https://json-schema.org/understanding-json-schema/reference/conditionals.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.