繁体   English   中英

JsonSchema:如何确保一个对象需要一个/特定的属性?

[英]JsonSchema: How make sure that an object requires one/specific properties?

我有一个要定义的对象,需要一个键或另一个特定的键。 基本上是一个简单的或:if(key1 || key2){->有效} else {->无效}

现在,我知道了“ require”关键字,但是据我所知,它不能有条件地要求键。 就我而言,我想完全将key1或key2存在。

{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "$id": "/my_schema",
  "type": "object",
  "properties": {
    "key1": {
      "type": "string"
    },
    "key2": {
      "type": "array",
      "items": {
        "type": "string"
      }
    },
    "key3": {
      "type": "array",
      "items": {
        "type": "string",
        "minItems": 1
      }
    },
    "key4": {
      "type": "object",
      "properties": {
        "begin": {
          "type": "number"
        },
        "end": {
          "type": "number"
        }
      }
    }
  },
  "required": [
    "key3", "key4"
  ]
}

如果可能的话,我在寻找可以在条件下定义对象的内容,例如:

"required": {
    "key1": if(someConditions), 
    "key2": if(someOtherConditions)
}

甚至这个:

"porperties":{
     "key1":{
         "type": someType,
         "required": if(someCondition)
     }
}

但是现在,我只想确保需要key1或key2,并且如果两者都不存在,则该架构无效。

为了验证至少必须有两个属性之一,可以使用anyOf块。

"properties": {...},
"required":[
   "key3", 
   "key4"
],
"anyOf": [
  {
    "required": [
      "key1"
    ]
  },
  {
    "required": [
      "key2"
    ]
  }
]

要根据您可以使用一些条件验证可用性if then else关键字。 例如,

如果key1 =“ 1”,则需要key2。 否则,需要key3

"if": {
  "key1": {
    "const": "1" // some simple condition 
  }
},
"then": {
  "required": [
    "key2"
  ]
},
"else": {
  "required": [
    "key3"
  ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM