无论嵌套在哪里,如何从架构本身引用架构(在这种情况下为B
?
我希望能够针对架构A
和针对架构B
进行验证。例如
from jsonschema import validate
validate(a, A)
validate(b, B)
为什么?对于单元测试和速度改进(如果B
之一失败,则不需要验证A
)。
模式A
引用模式B
,而B
引用自身(请参见下面的示例)。
我尝试了以下方法:
a)仅在针对definitions
进行验证的情况下,在A
中使用A
。验证B失败,jsonschema.exceptions.RefResolutionError: Unresolvable JSON pointer: 'definitions/b'
。这是有道理的,因为该定义仅存在于A
上。
from jsonschema import validate
B = {
"anyOf": [
{
"type": "object"
},
{
"type": "array",
"items": {"$ref": "#/definitions/b"}
}
]
}
A = {
"definitions": {
"b": B
},
"type": "array",
"items": {"$ref": "#/definitions/b"}
}
validate([], A)
validate([], B) # RefResolutionError
b)在"$id": "http://example.org/B"
中使用B
并将其自身引用为:{"$ref": "http://example.org/B"}
对不存在的URL进行实际的(不必要的http请求)。由于信息存在于文档中,因此无需发出请求。使用#B
之类的非URL尝试失败,并显示jsonschema.exceptions.RefResolutionError: unknown url type
。
from jsonschema import validate
B = {
"$id": "http://example.org/schema/B",
"anyOf": [
{
"type": "object"
},
{
"type": "array",
"items": {"$ref": "http://example.org/schema/B"}
}
]
}
A = {
"type": "array",
"items": {"$ref": "http://example.org/schema/B"}
}
validate([{}], A) # RefResolutionError: HTTP Error 404: Not Found
validate([{}], B) # RefResolutionError: HTTP Error 404: Not Found