【问题标题】:Is it possible to create a JSON Schema with allOf (multiple if and then) and $ref?是否可以使用 allOf(多个 if 和 then)和 $ref 创建 JSON Schema?
【发布时间】:2019-08-31 00:57:40
【问题描述】:

我正在尝试创建一个复杂的模式,该模式将检查属性的值,然后根据同一属性的值进行验证。我想知道是否可以在同一架构中使用 $ref 和 allOf ,如果可以,如何?我在让它工作时遇到了一些麻烦。值得注意的是,我正在使用 AJV。请在下面查看我的代码

{ 
  "$ref": "#/definitions/Welcome",
  "definitions": {
    "Welcome": {
      "properties": {
        "auth": {
          "type": "string",
          "enum": ["oauth1","oauth2"]
        },
        "environment": {
          "$ref": "#/definitions/Environment"
        }
      }
    },
    "Environment": {
      "properties": {
        "dev": {
          "type": "object"
        }
      }
    },
    "Oauth1": {
      "type": "object",
      "properties": {
        "temporary_credentials": {
          "type": "string"
        }
      }
    },
    "Oauth2": {
      "type": "object",
      "properties": {
        "auth_url": {
          "type": "string"
        }
      }
    }
  },
  "allOf": [
    {
      "if": {
        "auth": {
          "const": "oauth1"
        }
      },
      "then": {
        "environment": {
          "dev": {
            "$ref": "#/definitions/Oauth1
          }
        }
      }
    },
    {
      "if": {
        "auth": {
          "const": "oauth2"
        }
      },
      "then": {
        "environment": {
          "dev": {
            "$ref": "#/definitions/Oauth2
          }
        }
      }
    }
  ]
}

要针对 this 架构进行验证的示例 json 输入将是这样的

{
  "auth": "oauth1",
  "environment": {
    "dev": {
      "temporary_credentials": "xyzzy"
    }
  }
}

我觉得我的“then”语句或 allOf 的放置可能有错误。我会得到的错误类似于“$ref:路径“#”的架构中忽略的关键字。

【问题讨论】:

  • @gregsdennis mine 正在使用带有 "$ref" 的 "if" 和 "then" 感谢您的意见
  • 使用$ref 或内联模式都没有关系;逻辑(和解决方案)是相同的。不要同时使用*Ofif/then/else
  • 此外,then 块内的架构需要一些 properties 标注。
  • @gregsdennis 为什么不能 allOf 和 if/then/else 一起使用?我在我的模式中使用它;当我有一个 if/thens 列表时,我将它包装在一个 allOf 中,并且从来没有遇到过问题。

标签: json schema jsonschema json-schema-validator


【解决方案1】:

在草稿7 及之前的架构版本中,一旦您使用"$ref",该架构级别中的所有其他关键字都将被忽略。这就是错误告诉您的内容:因为您使用了$ref,所以忽略了其他关键字。

如果您只想在根级别使用$ref,诀窍是将其包装在"allOf" 中。

但是由于您在根级别已经有一个allOf,您只需将$ref 添加为allOf 的另一个分支,它就会起作用。

看起来像:

"allOf": [
{
  "$ref": "#/definitions/Welcome",
},
{
  "if": {
    "auth": {
      "const": "oauth1"
    }
    etc.

注意:在您发布的架构中,您有两个未闭合的字符串 "#/definitions/Oauth1"#/definitions/Oauth2。如果你在你的真实模式中有它,那将是无效的 JSON。

【讨论】:

  • 当您说“将 $ref 添加为 allOf 的另一个分支”时,我不太确定您的意思。如果“allOf”是一个对象数组,你的意思是我应该将“$ref”作为一个对象添加到该数组中吗?像这样的东西......“allOf”:[“$ref”:{}]。对这个很新,很抱歉有点慢
  • 好的,所以错误现在消失了,但验证器似乎没有从 ref 获取模式,因此无法正常工作。我的架构实际上与我发布的架构有点不同,而且更复杂。有什么方法可以联系你吗?
  • 我实际上能够弄清楚。谢谢你的一切
猜你喜欢
  • 2019-10-12
  • 2014-01-17
  • 2019-08-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
相关资源
最近更新 更多