【问题标题】:Properties based on enum value in JSON Schema基于 JSON Schema 中枚举值的属性
【发布时间】:2018-04-18 18:25:39
【问题描述】:

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

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

{
  "$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 架构中包含/要求一个字段?

【问题讨论】:

    标签: json schema jsonschema


    【解决方案1】:

    使用IF..Then..Else new in Draft-07

    {
      "$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"]
        }
      }
    }
    

    使用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"]
          }
        ]
      }
    }
    

    进一步阅读

    【讨论】:

    • 但是在使用$ref的时候你是怎么做到的??我在不同的文件中定义了一个枚举,我如何伪造一个对象来为该实例中的每个枚举值提供一个属性?
    猜你喜欢
    • 2022-01-23
    • 2020-10-07
    • 2020-07-19
    • 2022-12-17
    • 2019-03-23
    • 1970-01-01
    • 2020-11-04
    • 2020-06-14
    • 1970-01-01
    相关资源
    最近更新 更多