【问题标题】:How to make a required property if another property is empty and vice versa, in the JSON Schema如果另一个属性为空,如何在 JSON 模式中创建一个必需的属性,反之亦然
【发布时间】:2020-03-27 15:41:04
【问题描述】:

我目前的 json 架构定义是这样的

{
    "type": "object",
    "properties": {
        "name": {
            "type": "string",
            "minLength": 1
        },
        "description": {
            "type": "string",
            "minLength": 1
        },
        "input": {
            "type": "array",
            "items": {
                "type": "object",
                "properties": {
                    "name": {
                        "type": "string"
                    },
                    "description": {
                        "type": "string"
                    },
                    "type": {
                        "type": "string"
                    }
                },
                "required": ["name", "description", "type"]
            }
        },
        "output": {
            "type": "array",
            "maxItems": 1,
            "items": {
                "type": "object",
                "properties": {
                    "description": {
                        "type": "string",
                        "minLength": 1
                    },
                    "type": {
                        "type": "string"
                    }
                },
                "required": ["description", "type"]
            }
        }
    },
    "required": ["name", "description"]
}

所以我需要验证以下条件的方案:

  1. 如果输入数组和输出数组都为空,则两者都必须;
  2. 如果输入数组不为空,那么输出数组应该不需要;
  3. 如果输出数组不为空,则输入数组不应该是必需的;

提前谢谢你。

【问题讨论】:

  • 我可以为您提供解决方案,但目前还不行。我希望其他时区的人会打败我,但如果不是,我会回来的! =]

标签: json validation jsonschema


【解决方案1】:

您的第一个条件是我们需要处理的唯一条件。默认情况下,所有属性都是可选的,因此您的条件 2 和 3 转换为类似“如果输入数组不为空,则不执行任何操作”。

有几种方法可以实现第一个条件,但我建议如下。

"allOf": {
  "if": {
    "properties": {
      "input": { "const": [] },
      "output": { "const": [] }
    }
  },
  "then": { "required": ["input", "output"] }
}

【讨论】:

    【解决方案2】:

    您的三个要求似乎都在 json 模式中自我实现。

    如果输入数组和输出数组都为空,则两者都必须是必需的

    如果inputoutput 是空数组,它们已经存在,所以说它们是必需的是多余的。有点像,“如果 x 存在值 [],则 x 必须存在”。 Jason 的架构正确地表达了您的表述方式,但我认为该架构不会导致验证错误。

    Jason 在第 2 点和第 3 点的回答是正确的。

    我建议您考虑一些您希望验证失败的示例实例(并在此处将它们添加到您的问题中),这将有助于构建一个添加适当约束的架构。

    【讨论】:

    • 感谢您的评论。所以,可能,我没有正确表达自己。架构应在以下情况下显示错误:1. input 存在但包含 0 个元素。
    猜你喜欢
    • 1970-01-01
    • 2015-04-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 2020-07-19
    • 2021-11-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多