【问题标题】:json schema, conditional dependency by property being present or notjson模式,属性的条件依赖是否存在
【发布时间】:2017-10-01 07:41:15
【问题描述】:

我有这个架构要求,如果 A 和 B 不存在,C 必须存在,如果 C 存在,A 和 B 不应该存在。

例如:

{
  "group1": {
    "a": 10
  },
  "group2": {
    "group3": {
      "b": 30
    }
  },
  "group4": {
    "c": 20
  }
}

如果存在a,则bc 不应在json 中。 如果bc 存在,则a 不应在json 中。

我可以看到在 v6 json 架构规范中有一些关键字 switch 可以帮助满足此要求但无法使其工作。

目前的规范是否可以进行架构验证?

【问题讨论】:

    标签: json jsonschema json-schema-validator


    【解决方案1】:

    draft-06 是当前的规范,但还没有条件。 Draft-07 有 if/then/else 使用,您可以:

    {
      "if": {"required": ["a"]},
      "then": {"not": {"$ref": "#/definitions/bc"}},
      "else": {"$ref": "#/definitions/bc"},
      "definitions": {
        "bc": {
          "anyOf": [
            {"required": ["b"]},
            {"required": ["c"]}
          ]
        }
      }
    }
    

    目前 Ajv 支持 if/then/else 和 ajv-keywords。

    任何条件都可以不用 if/then/else 使用关键字 anyOf、allOf 和 not 来表达:

    {
      "anyOf": [
        {"allOf": [ifSchema, thenSchema]},
        {"allOf": [{"not": ifSchema}, elseSchema]}
      ]
    }
    

    【讨论】:

    • 谢谢!第二个选项在我的示例中如何工作?
    • 只需替换第一个样本中的子模式
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-08
    • 1970-01-01
    • 2010-11-19
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    相关资源
    最近更新 更多