[英]Removing the duplication in a JSON schema that uses oneOf (v4 or v5)
我有一組 2 個始終可選的屬性,但只有在另一個(始終需要)布爾屬性的值為 true 時才允許出現。
這始終是可選的,但並不總是允許的屬性被命名為: max_recurrences
和recurrence_arguments
。 它們所依賴的值為true
的布爾屬性被命名為: recurring
。
我想出了下面的模式,我認為它有效,但我正在復制oneOf
數組的每個項目中的所有其他屬性。 我正在尋找一種方法來避免這種重復。
{
"id": "plan_schedule",
"type": "object",
"oneOf": [
{
"properties": {
"start_date": {
"type": "string",
"format": "date-time"
},
"end_date": {
"type": "string",
"format": "date-time"
},
"trigger": {
"$ref": "re_non_empty_string"
},
"arguments": {
"type": "object",
"minProperties": 1
},
"recurring": {
"type": "boolean",
"enum": [true],
},
"max_recurrences": {
"type": "integer",
"minimum": 1
},
"recurrence_arguments": {
"type": "object",
"minProperties": 1
}
}
},
{
"properties": {
"start_date": {
"type": "string",
"format": "date-time"
},
"end_date": {
"type": "string",
"format": "date-time"
},
"trigger": {
"$ref": "re_non_empty_string"
},
"arguments": {
"type": "object",
"minProperties": 1
},
"recurring": {
"type": "boolean",
"enum": [false],
},
}
}
],
"additionalProperties": false,
"required": ["start_date", "trigger", "recurring"]
}
誰能幫我嗎? 我想使用 v4,但如果有幫助,我願意使用 v5。
為了進一步澄清,我希望只需要在整個架構中列出屬性: start_date
、 end_date
、 trigger
和arguments
一次。
JSON 架構草案 04:
{
"type": "object",
"properties": {
"recurring": {
"type": "boolean"
}
// all other properties
}
"additionalProperties": false,
"required": ["start_date", "trigger", "recurring"]
"anyOf": [
{
"properties": { "recurring": { "enum": [true] } }
},
{
"properties": { "recurring": { "enum": [false] } },
"not": {
"anyOf": [
{ "required": ["max_recurrences"] },
{ "required": ["recurrence_arguments"] }
}
}
}
]
}
如果您使用 Ajv(我認為是因為 v5 是其他任何地方都沒有使用的概念),您可以使用為 Draft-07 提出的自定義關鍵字“if/then/else”和“prohibited”來簡化上述內容,並獲得一些支持 - 他們在ajv-keywords中定義。 “anyOf”可以替換為:
"if": { "properties": { "recurring": { "enum": [false] } } },
"then": { "prohibited": ["max_recurrences", "recurrence_arguments"] }
編輯:
實際上,使用“dependencies”關鍵字可以更簡單地完成,而無需任何自定義關鍵字。 而不是“anyOf”:
"dependencies": {
"max_recurrences": { "$ref": "#recurring" },
"recurrence_arguments": { "$ref": "#recurring" }
},
"definitions": {
"recurring": {
"id": "#recurring",
"properties": {
"recurring": { "enum": [true] }
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.