是否可以使用allOf(多个if和then)和$ ref创建一个JSON Schema?

问题描述 投票:0回答:1

我正在尝试创建一个复杂的模式,它将检查属性的值,然后根据相同属性的值进行验证。我想知道是否有可能在同一架构中使用$ 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
          }
        }
      }
    }
  ]
}

要针对此模式进行验证的示例json输入将是这样的

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

我觉得我的“then”语句中可能存在错误,或者只是放置allOf。我会得到的错误是这样的“$ ref:在路径模式中忽略的关键字”#“”。

json schema jsonschema json-schema-validator
1个回答
1
投票

在架构版本(包括draft7)中,一旦使用"$ref",架构级别中的所有其他关键字都将被忽略。这就是错误告诉你的:因为你使用了$ref,其他关键字被忽略了。

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

但是因为你已经在根级别有一个allOf,你可以添加$ref作为allOf的另一个分支,它会工作。

那看起来像是:

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

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

© www.soinside.com 2019 - 2024. All rights reserved.