微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 JSON Schema 实现条件嵌套属性

如何解决如何使用 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)$'">]。不知道这里出了什么问题

解决方法

我认为你把它复杂化了——当然只是 if/then/else?

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。