首页 > 解决方案 > 如何使用 JSON Schema 实现条件嵌套属性

问题描述

我有基本的 json 架构base.schema.json

{
  "$id": "base.schema.json",
  "type": "object",
  "properties": {
    "remote_os": {
      "default": "Windows",
      "enum": [
        "Linux",
        "Windows" ]
     }
  },
  "required": ["remote_os"]
}

现在在另一个 json 中引用了模式定义

{
  "$id": "update.schema.json",
  "properties": {
    "common_data": {
      "$ref": "base.schema.json"
    }
  },
  "allOf": [
    {
      "if": {
        "properties": {
          "common_data": {
            "remote_os": {
              "const": "Windows"
            }
          }
        }
      },
      "then": {
        "properties": {
          "file": {
            "pattern": "^(.*.)(exe)$"
          }
        }
      }
    },
    {
      "if": {
        "properties": {
          "common_data": {
            "remote_os": {
              "const": "Linux",
              "required": [
                "remote_os"
              ]
            }
          }
        }
      },
      "then": {
        "properties": {
          "file": {
            "pattern": "^(.*.)(bin)$"
          }
        }
      }
    }
  ]
}

基本上添加if-else逻辑以确保remote_os=Linux file应该结束.bin并且remote_os=Windows file应该结束.exe
现在我正在尝试验证以下数据

{
  "common_data": {
    "remote_os": "Linux"
  },
  "file": "abc.bin"
}

[<ValidationError: "'abc.bin' does not match '^(.*.)(exe)$'">]. 不知道这里有什么问题

标签: jsonschemajson-schema-validatorpython-jsonschema

解决方案


我认为你把它复杂化了——如果/那么/其他?

{
  "if": {
    "properties": { "common_data": "properties": { "remote_os": { "const": "Windows" } } }
  },
  "then": {
    "properties": { "file": { "pattern": "^(.*.)(exe)$" } }
  },
  "else": {
    "properties": { "file": { "pattern": "^(.*.)(bin)$" } }
  }
}

推荐阅读