JSONSchema本地自引用(递归)

时间:2018-07-18 00:49:23

标签: jsonschema

无论嵌套在哪里,如何从架构本身引用架构(在这种情况下为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

0 个答案:

没有答案