【问题标题】:JSONSchema local self-reference (recursion)JSONSchema 本地自引用(递归)
【发布时间】:2018-07-18 00:49:22
【问题描述】:

无论嵌套在何处,我如何才能从自身引用架构(在本例中为 B)?

我希望能够针对架构 A 进行验证针对架构 B。例如

from jsonschema import validate
validate(a, A)
validate(b, B)

为什么?对于单元测试和速度改进(如果 B 之一失败,我不需要验证 A)。

架构 A 引用架构 BB 引用自身(参见下面的示例)。

我尝试了以下方法:

a) 仅当针对 A 进行验证时,在 A 中使用 definitions 才有效。验证 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)B 中使用"$id": "http://example.org/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

【问题讨论】:

  • 你好!看起来你没有分享别人给你答案所需的一切。您能否提供完整的 JSON 架构?你能告诉我们你正在使用的图书馆吗?
  • from jsonschema import validate 是 python 代码(但任何其他验证器都会产生与我假设相同的结果)。我已经添加了我尝试过的示例,您可以复制并粘贴它们以进行测试。

标签: jsonschema


【解决方案1】:

我遇到了类似这样的问题。我发现将我的 jsonschema 模块从版本 3 的某个地方升级到 jsonschema >= 4.3.2 立即修复了它,所以可能只是一个错误。

pip install --upgrade jsonschema

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-26
    • 2011-02-11
    • 2019-07-18
    • 2011-01-17
    相关资源
    最近更新 更多