如果我使用JSON模式的if-else条件,是否可以针对JSON中存在的任何其他键引发错误?

问题描述 投票:1回答:1

我有一个用例,我想根据另一个键的值来检查JSON中存在的键。

示例JSON-1:

{ 
  "key_name" : "value1",
  "foo" : "random_value1"
}

示例JSON-2:

{ 
  "key_name" : "value2",
  "bar" : "random_value2"
}

根据这些示例,

规则1。如果“ key_name”的值为“ value1”,则only“ foo”键应出现在JSON中。

规则2。如果“ key_name”的值为“ value2”,则only“ bar”键应出现在JSON中。

我已经编写了以下JSON模式以验证这些JSON:

{
  "type": "object",
  "properties": {
    "key_name": {
      "type": "string",
      "enum": [
        "value1",
        "value2"
      ]
    },
    "foo": {
      "type": "string"
    },
    "bar": {
      "type": "string"
    }
  },
  "required": [
    "key_name"
  ],
  "additionalProperties": false,
  "allOf": [
    {
      "if": {
        "properties": {
          "key_name": {
            "enum": [
              "value1"
            ]
          }
        }
      },
      "then": {
        "required": [
          "foo"
        ]
      }
    },
    {
      "if": {
        "properties": {
          "key_name": {
            "enum": [
              "value2"
            ]
          }
        }
      },
      "then": {
        "required": [
          "bar"
        ]
      }
    }
  ]
}

现在,按照规则,以下JSON无效,并且应该引发错误。

{ 
  "key_name" : "value1",
  "foo" : "random_value1",
  "bar" : "random_value2"
}

OR

{ 
  "key_name" : "value2",
  "bar" : "random_value2",
  "foo" : "random_value"
}

但是,上述JSON模式失败。它仅根据“ key_name”的值检查“ foo” /“ bar”键是否正确。它无法检查是否存在任何新密钥。

如何处理?

json jsonschema json-schema-validator python-jsonschema
1个回答
0
投票

这里已经回答:Mutually exclusive property groups

此外,您可以在这里找到很棒的概述:jsonSchema attribute conditionally required


对于您的特定示例,想到以下方法:

  1. "not": { "required": ["bar"] }添加到您的第一个then子句中以指示不允许使用"bar"。然后,第二个"foo"子句中的then也是如此。
  2. 如果总是只允许"key_name"和一个其他属性,您也可以在主模式中简单地添加"maxProperties": 2
© www.soinside.com 2019 - 2024. All rights reserved.