【问题标题】:How to implement conditional nested properties with JSON Schema [duplicate]如何使用 JSON Schema 实现条件嵌套属性 [重复]
【发布时间】:2021-07-28 12:04:20
【问题描述】:

我有基本的 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 应以.binremote_os=Windows file.exe 结束
现在我正在尝试验证以下数据

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

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

【问题讨论】:

  • "'abc.bin' 难以理解的地方与 '^(.*.)(exe)$'" 不匹配
  • 对于验证数据 remote_os = Linux 和 JSON Schema 中的 if-else update.schema.json file 应该以 bin 扩展名结束。所以我的验证数据只是正确的,它不应该引发ValidationError
  • 啊,我明白了。我建议一个更好的问题标题:“How to check nested properties with JSON Schema if else” 而不是“not working”。
  • 感谢反馈,我现在改标题了。
  • 在示例中,参考架构定义是相同 JSON 的一部分,我希望它也适用于本地文件参考。仍然没有找到if-else 应该去的地方。一些例子真的很有帮助

标签: jsonschema json-schema-validator python-jsonschema


【解决方案1】:

我认为你把事情复杂化了——如果/那么/否则就很粗暴吗?

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

【讨论】:

  • 实际上试过了,但它不起作用。它总是在寻找 "pattern": "^(.*.)(exe)$" 模式,不管 remote_osWindows or Linux
  • 您的架构中有错误(问题和答案):您在“common_data”和“remote_os”之间缺少一个额外的"properties: { ... 。没有可识别关键字的模式总是正确的,这就是为什么“then”路径总是在评估。
猜你喜欢
  • 2019-11-25
  • 1970-01-01
  • 2021-09-19
  • 2020-08-09
  • 1970-01-01
  • 2016-07-06
  • 2012-08-05
  • 2016-04-22
  • 2023-03-09
相关资源
最近更新 更多