如何仅在不存在其他属性时才允许一个属性,并在JSON模式中允许其他属性 [英] How to allow one property only if other is not present and allow any of other propeties in json schema

查看:101
本文介绍了如何仅在不存在其他属性时才允许一个属性,并在JSON模式中允许其他属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有六个属性:姓名,年龄,电话,deletePhone,地址,deleteAddress.

I have six properties: name, age, phone, deletePhone, address, deleteAddress.

我想创建允许上述任何属性的模式,但phone不应与deletePhone一起出现,而address不应与deleteAddress一起出现(反之亦然).

I want to create schema that allows anyOf above properties but phone should not be present with deletePhone and address should not be present with deleteAddress(and vice versa).

我尝试过以下模式:

{
    "type": "object",
    "properties": {
      "name": {
        "type": "string"
      },
      "age": {
        "type": "number"
      },
      "phone": {
        "type": "number"
      },
      "deletePhone": {
        "type": "boolean"
      },
      "address": {
        "type": "string"
      },
      "deleteAddress": {
        "type": "boolean"
      }
    },
    "allOf": [
      {
        "oneOf": [
          {
            "required": ["phone"]
          },
          {
            "required": ["deletePhone"]
          }
        ]
      },
      {
        "oneOf": [
          {
            "required": ["address"]
          },
          {
            "required": ["deleteAddress"]
          }
        ]
      }
    ]
}

它证实为真

{
    "name": "my name",
    "address": "some addr",
    "phone": 34
}

并验证

{
    "address": "some addr",
    "phone": 34,
    "deletePhone": true
}

这是正确的,但它也验证了错误的

which is correct but it also validates false for

{
    "phone": 34
}
or
{
    "name": "some name"
}

我想验证真,我知道我缺少anyOf,oneOf的某种组合,还是有更好的方法?

Which i want to validate true, i know i'm missing some combination of anyOf, oneOf, Or is there any better way?

推荐答案

我认为这是最简单的解决方案.

I think this is the simplest solution.

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "number" },
    "phone": { "type": "number" },
    "deletePhone": { "type": "boolean" },
    "address": { "type": "string" },
    "deleteAddress": { "type": "boolean" }
  },
  "allOf": [
    { "not": { "required": ["phone", "deletePhone"] } },
    { "not": { "required": ["address", "deleteAddress"] } }
  ]
}

这篇关于如何仅在不存在其他属性时才允许一个属性,并在JSON模式中允许其他属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆