JSON 模式来检查是否只有一个数组项包含属性

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

有没有办法检查某个属性是否存在于数组中,但仅存在于其中一项中?

在以下示例中,“文件名”和“格式”必须至少出现在一项且仅出现在一项数组项中。

有效的 JSON 示例:

{
    "myarray": [
        {
            "name": "Example 1"
        },
        {
            "filename": "example.txt",
            "format": "txt"
        }
    ]
}
{
    "myarray": [
        {
            "name": "Example 2"
            "filename": "example.txt"
        },
        {
            "format": "txt"
        }
    ]
}

无效的 JSON 示例:

{
    "myarray": [
        {
            "name": "Example 3"
            "filename": "example.txt"
            "format": "txt"
        },
        {
            "filename": "example3.txt"
        }
    ]
}

我能够通过以下模式实现这一目标,但它仅适用于一个属性。当我添加格式时,它对“文件名”或“格式”都不起作用。

"myarray": {
    "type": "array",
    "items": {
        "type": "object",
        "properties": {
            "filename": {
                "type": "string"
            }
        }
    },
    "additionalProperties": false,
    "contains": {
        "required": [
            "filename"
        ]
    },
    "not": {
        "items": {
            "required": [
                "filename"
            ],
            "minProperties": 1
        }
    }
}
json jsonschema json-schema-validator
1个回答
0
投票

您可以使用

allOf
,因为您需要匹配多个,而
minContains
maxContains
,因为您至少有一个且只有一个条件。

{
  "properties": {
    "myarray": {
      "type": "array",
      "items": {
        "type": "object",
        "properties": {
          "filename": {
            "type": "string"
          },
          "format": {
            "type": "string"
          }
        }
      },
      "allOf": [
        {
          "contains": {
            "required": [
              "filename"
            ]
          },
          "minContains": 1,
          "maxContains": 1
        },
        {
          "contains": {
            "required": [
              "format"
            ]
          },
          "minContains": 1,
          "maxContains": 1
        }
      ]
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.