【问题标题】:How Do I Require that a Sub-Property Must Exist Using JSON Schema?如何使用 JSON 模式要求子属性必须存在?
【发布时间】:2023-02-10 03:46:04
【问题描述】:

在 JSON 架构中,我可以使用 require 来确保属性存在于层次结构的同一级别,但我无法验证嵌套的属性。

假设我有以下 JSON 模式:

{
    "type": "object",
    "properties": {
        "my_type": {
            "type": "string"
        },
        "t1_data": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        },
        "t2_data": {
            "type": "object",
            "properties": {
                "id": {
                    "type": "string"
                }
            }
        }
    }
}

我将如何指定以下验证?

  • 如果my_type == "type1",则t1_data.id必须存在
  • 如果my_type == "type2",则t2_data.id必须存在
  • 如果my_type是其他任何东西,验证通过

我试过使用 requireanyOf 构造,但我只能让它们在层次结构的同一级别工作。

谢谢,

【问题讨论】:

    标签: json schema jsonschema


    【解决方案1】:

    一种可能的解决方案是组合 allOfif-then。这有点冗长,但我不知道有什么更短的方法。这是案例“type1”的架构:

    {
      "$schema": "https://json-schema.org/draft/2019-09/schema",
      "description": "JSON schema generated with JSONBuddy https://www.json-buddy.com",
      "type": "object",
      "properties": {
        "my_type": {
          "type": "string"
        },
        "t1_data": {
          "type": "object",
          "properties": {
            "id": {
              "type": "string"
            }
          }
        },
        "t2_data": {
          "type": "object",
          "properties": {
            "id": {
              "type": "string"
            }
          }
        }
      },
      "allOf": [
        {
          "if": {
            "properties": {
              "my_type": {
                "const": "type1"
              }
            }
          },
          "then": {
            "properties": {
              "t1_data": {
                "type": "object",
                "properties": {
                  "id": {
                    "type": "string"
                  }
                },
                "required": [ "id" ]
              }
            }
          }
        }
      ]
    }
    

    “type2”与allOf 数组中的下一个模式完全相同。

    【讨论】:

      猜你喜欢
      • 2021-02-19
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      • 2015-10-20
      • 2023-01-23
      • 2021-09-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多