如何使用JSON模式实现条件嵌套属性 [英] How to implement conditional nested properties with JSON Schema

查看:69
本文介绍了如何使用JSON模式实现条件嵌套属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有基本的json模式 base.schema.json

I have base json schema base.schema.json

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

现在在另一个json中引用了架构定义

Now referenced the schema definition in another 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 结束code>和 remote_os = Windows file 应该以 .exe
结尾现在,我正在尝试根据以下数据进行验证

Basically adding the if-else logic to make sure for remote_os=Linux file should ended up with .bin and remote_os=Windows file should ended up with .exe
Now I am trying to validate against below data

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

[< ValidationError:"'abc.bin'与'^(.*.)(exe)$'">]] 不匹配.不确定这是怎么回事

[<ValidationError: "'abc.bin' does not match '^(.*.)(exe)$'">]. Not sure what's wrong here

推荐答案

我认为您过于复杂了-只是在/然后/否则?

I think you are over complicating it - surly just if/then/else?

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

这篇关于如何使用JSON模式实现条件嵌套属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆