当另一个参数不存在时需要具有 JSON 架构的参数

requiring a param with JSON Schema when another param is not present

更新: 添加要求

我正在尝试实现一个像这样工作的 JSON 模式……

给定以下参数:foobarbazonetwo

应满足以下条件之一

当然,如果提供的任何参数在模式中,那么应该引发适当的错误。

经过大量的欺骗,,这是我的尝试,但并不奏效

{
    "type": "object",
    "properties": {
        "foo": { "type": "string" },
        "bar": { "type": "string" },
        "baz": { "type": "string" }
    },
    "oneOf": [
        {
            "not": {
                "properties": { "foo": { "const": "" } },
                "required": []
            }
        },
        { "required": [ "one", "two" ] }
    ]
}

我也尝试了以下但没有成功

{
    "type": "object",
    "properties": {
        "foo": { "type": "string" },
        "bar": { "type": "string" },
        "baz": { "type": "string" }
    },
    "dependencies": {
        "not": {
            "foo": { "required": ["one", "two"] }
        }
    }
}

我怀疑这里可能有一两个隐藏的要求,但这里有一个基于您的要求的解决方案。让我知道我是否遗漏了什么,我会更新我的答案。

您的大部分要求都是 JSON 架构中的默认行为,因此您无需执行任何操作。

  • either no param exists

默认情况下所有属性都是可选的,所以这里不用做什么

  • if foo exists - then one and two are not required

同样,可选是默认设置,因此此处无需执行任何操作

  • if one or more params exist then [and] any param(s) other than foo exist(s) - then one and two are required

最好的表达方式是 if/then。如果“foo”是可选的,表达“除 foo 之外的任何参数”有点复杂,所以我把它放在 definitions 中以使其更容易阅读。

if any params are provided that are not in the schema then an appropriate error should be raised.

additionalProperties 关键字可以解决这个问题。你只需要加上“一”和“二”即可。

{
  "type": "object",
  "properties": {
    "foo": { "type": "string" },
    "bar": { "type": "string" },
    "baz": { "type": "string" },
    "one": {},
    "two": {}
  },
  "additionalProperties": false,
  "if": { "$ref": "#/definitions/has-property-other-than-foo" },
  "then": { "required": ["one", "two"] },
  "definitions": {
    "has-property-other-than-foo": {
      "if": { "required": ["foo"] },
      "then": { "minProperties": 2 },
      "else": { "minProperties": 1 }
    }
  }
}