首页 文章

JSON模式:类型中的模式

提问于
浏览
1

我正在尝试创建一个复杂的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"]
}

如果 q1 的答案为真,则模拟需要 sq1 答案的条件依赖关系到一个模式 combined_schema .

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

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

有人可以帮助我将维基示例应用于我的现实世界问题吗?

2 回答

  • 0

    我找到了答案 . 他们的关键是使用 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"]
        }
    }
    
  • 0

    您的答案的架构不是有效的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(免责声明:我创建了它) .

相关问题