基于 JSON Schema 中的枚举值的属性

Dvi*_*irm 6 schema json jsonschema

我正在构建一个 json 模式定义,它具有一组固定的控件,我目前使用enum. 但是,并非所有属性都与所有控件相关。

options如果controlType=,我只想要求一个属性dropdown

{
  "$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"}
      }
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

如何有条件地在 json 模式中包含/需要一个字段?

Kyl*_*Mit 8

在 Draft-07 中使用newIF..Then..Else

{
  "$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"}
      }
    },
      
    "if": {
      "properties": {
        "controlType": {"const": "dropdown"}
      }
    },
    "then": {
      "required": ["options"]
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

使用oneOfanyOf

如果您的属性具有有限数量的可接受值(例如枚举),但每个可能的值都需要单独映射,则这会很有用。

{
  "$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"]
      }
    ]
  }
}
Run Code Online (Sandbox Code Playgroud)

进一步阅读