基于JSON架构中的枚举值的属性 [英] Properties based on enum value in JSON Schema
本文介绍了基于JSON架构中的枚举值的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在构建一个json模式定义,该定义具有一组固定的控件,而这些控件目前仅受 enum
限制.但是,并非所有属性都与所有控件相关.
I'm building a json schema definition which has a fixed set of controls that I've currently limited with an enum
. However, not all properties are relevant for all controls.
如果 controlType
= 下拉
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"properties": {
"controlType": {
"type": "string",
"enum": ["title", "dropdown", "button"]
},
"options:": {
"type": "array",
"items": {"type": "string"}
}
}
}
}
我如何有条件地在json模式中包含/要求一个字段?
How can I conditionally include / require a field in a json schema?
推荐答案
使用 IF.Then..Else
"if": {
"properties": {
"controlType": {"const": "dropdown"}
}
},
"then": {
"required": ["options"]
}
}
}
使用 oneOf
或 anyOf
如果您的属性具有有限数量的可接受值(例如枚举),但是每个可能的值都需要单独映射,这将很有用.
Use oneOf
or anyOf
This can be useful if you have a property that has a limited number of acceptable values (such as an enum), but each possible value needs to be individually mapped.
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"properties": {
"controlType": {
"type": "string",
"enum": ["title", "dropdown", "button"]
},
"options:": {
"type": "array",
"items": {"type": "string"}
}
},
"anyOf": [
{
"properties": {
"controlType": {"const": "dropdown"}
},
"required": ["controlType", "options"]
},
{
"properties": {
"controlType": {"const": "title"}
},
"required": ["controlType"]
},
{
"properties": {
"controlType": {"const": "button"}
},
"required": ["controlType"]
}
]
}
}
进一步阅读
oneOf
或 anyOf
oneOf
or anyOf
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "array",
"items": {
"type": "object",
"properties": {
"controlType": {
"type": "string",
"enum": ["title", "dropdown", "button"]
},
"options:": {
"type": "array",
"items": {"type": "string"}
}
},
"anyOf": [
{
"properties": {
"controlType": {"const": "dropdown"}
},
"required": ["controlType", "options"]
},
{
"properties": {
"controlType": {"const": "title"}
},
"required": ["controlType"]
},
{
"properties": {
"controlType": {"const": "button"}
},
"required": ["controlType"]
}
]
}
}
查看全文