json 模式验证 - 条件属性

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

我有一个格式如下的 json 对象

{
    "notificationType": "Directed",
    "userPaths": [
        "organization.SsoId"
    ],
    "id": "d15f83f3-f393-4839-ae72-a1e732219bb4",
}

我有一个模式验证如下

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "notificationType": {
      "type": "string"
    },
    "userPaths": {
      "type": "array",
      "items": [
        {
          "type": "string"
        }
      ]
    },
    "id": {
      "type": "string"
    }
  },
  "required": [
    "notificationType",
    "userPaths",
    "id"
  ]
}

我需要验证如果 notificationType 值为

Directed
那么 userPaths 需要至少有一项

试试这个

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "type": "object",
  "properties": {
    "notificationType": {
      "type": "string"
    },
    "userPaths": {
      "type": "array",
      "items": [
        {
          "type": "string"
        }
      ]
    },
    "id": {
      "type": "string"
    }
  },
  "if": {
    "notificationType": {
        "const": "Directed"
    }
  },
  "then": {
    "userPaths": {
        "type": "array",
        "items": {
            "type": "string",
            "minimum": 0
        }
    }
  },
  "required": [
    "notificationType",
    "userPaths",
    "id"
  ]
}

并在 https://www.jsonschemavalidator.net/ 进行测试,更改值并从 userPaths 数组中删除项目,它仍然表示这是有效对象。

如果有人能指出我出错的地方以及我需要做些什么来解决这个问题,我将不胜感激。

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

您走在正确的轨道上,但是您需要对架构进行一些更改才能实现所需的验证行为。这是更新后的架构:

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "type": "object",
  "properties": {
    "notificationType": {
      "type": "string"
    },
    "userPaths": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "id": {
      "type": "string"
    }
  },
  "required": [
    "notificationType",
    "userPaths",
    "id"
  ],
  "allOf": [
    {
      "if": {
        "properties": {
          "notificationType": {
            "const": "Directed"
          }
        },
        "required": ["notificationType"]
      },
      "then": {
        "properties": {
          "userPaths": {
            "type": "array",
            "items": {
              "type": "string"
            },
            "minItems": 1
          }
        },
        "required": ["userPaths"]
      }
    }
  ]
}

使用这个更新的模式,强制执行所需的验证行为。如果“notificationType”设置为“Directed”,则“userPaths”数组必须至少包含一项。以下是所做更改的细目:

  1. 升级到 draft-07 schema:虽然这对于这个特定案例不是必需的,但建议使用更新版本的 schema。撰写本文时的最新版本是 draft-2020-12,但 draft-07 得到更广泛的支持并且适用于此用例。

  2. 将“allOf”与“if”和“then”一起使用:这可确保将条件正确应用于模式。 “if”块检查“notificationType”是否为“Directed”,“then”块在“userPaths”数组上强制执行“minItems”约束。

现在,当您使用 JSON 数据测试此架构时,它应该会产生预期的验证结果:

  • 如果“notificationType”等于“Directed”,则“userPaths”数组必须至少有一项。
  • 如果“notificationType”不是“Directed”,则“userPaths”数组没有额外的限制。

您可以使用相同的 JSON 模式验证器测试这个更新后的模式

© www.soinside.com 2019 - 2024. All rights reserved.