【问题标题】:JSON schema: schemas in typesJSON 模式:类型中的模式
【发布时间】:2016-12-21 10:18:22
【问题描述】:

我正在尝试创建一个复杂的 JSON 模式,该模式尝试使用条件依赖项,而无需访问 OneOf、AnyOf 等

我基本上是在尝试结合

const schema1 = {
    type: "object",
    properties: {
        q1: {
            type: "boolean",
            enum: [false]
        }
    },
    required: ["q1"]
}

const schema2 = {
    type: "object",
    properties: {
        q1: {
            type: "boolean",
            enum: [true]
        }
        sq1: {
            type: "boolean"
        }
    },
    required: ["q1", "sq1"]
}

进入一个模式combined_schema,从而模拟条件依赖,如果q1 的答案为真,则需要sq1 的答案。

在 JSON 模式 wiki 中,我读到 AnyOf 将替换类型中的“模式”,但查看示例我不确定如何在特定情况下使用它({“schema1”:“here” } 部分非常混乱。

https://github.com/json-schema/json-schema/wiki/anyOf,-allOf,-oneOf,-not

有人可以帮我将 wiki 示例应用到我的现实问题吗?

【问题讨论】:

    标签: json jsonschema


    【解决方案1】:

    我找到了答案。他们的关键是使用refs

    {
        "type": [
                    {"$ref": "#/schema1"},
                    {"$ref": "#/schema2"}
                ],
        "schema2":{
            "type": "object",
            "properties": {
                "q1": {
                    "type": "boolean",
                    "enum": [true]
                },
                "sq1": {
                    "type": "boolean"
                }
            },
        "required": ["q1", "sq1"]
        },
        "schema1": {
            "type": "object",
            "properties": {
                "q1": {
                    "type": "boolean",
                    "enum": [false]
                }
            },
            "required": ["q1"]
        }
    }
    

    【讨论】:

    • 我也必须使用旧的 jsonSchema 库。这是正确的答案。在旧版本的 jsonSchema 中,您必须使用 type 属性中的列表。 "$ref" 是可选的。
    【解决方案2】:

    您回答的架构不是有效的 JSON 架构。您可以使用 anyOf 关键字:

    {
        type: "object",
        required: ["q1"]
        anyOf: [
            {
                properties: {
                    q1: { enum: [false] } // no need for type here
                }
            },
            {
                properties: {
                    q1: { enum: [true] },
                    sq1: { type: "boolean" }
                },
                required: ["sq1"]
            }
        ]
    }
    

    还有 Ajv 中实现的 JSON-Schema v5 提案中的关键字 switch(免责声明:我创建了它)。

    【讨论】:

    • anyOf 是不可能的,正如我的问题中明确指出的那样。
    • 唯一的选择是v5切换然后...为什么你需要避免anyOf?
    猜你喜欢
    • 1970-01-01
    • 2020-09-14
    • 1970-01-01
    • 2020-02-05
    • 1970-01-01
    • 2015-10-15
    • 2016-02-29
    • 2014-05-21
    • 2011-12-12
    相关资源
    最近更新 更多