Is it possible to create a JSON Schema with allOf (multiple if and then) and $ref?

荒凉一梦 提交于 2020-05-29 10:15:50

问题


I am trying to create a complex schema that will check for the value of a property and then validate according to the value of that same property. I am wondering if it's possible to use $ref and allOf in the same schema and if so, how? I am having some trouble getting this to work. It may be important to note that I am using AJV. Please see my code below

{ 
  "$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
          }
        }
      }
    }
  ]
}

A sample json input to be validated against this schema would be something like this

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

I feel like there might be an error in my "then" statements or simply the placement of the allOf. The error I would get is something like this "$ref: keywords ignored in schema at path "#"".


回答1:


In schema version up to and including draft7, once you use "$ref", all other keywords in that level of the schema are ignored. That's what the error is telling you: because you used $ref, other keywords are ignored.

If you only want to use a $ref at the root level, the trick is to wrap it in an "allOf".

But since you already have an allOf at the root level, you can just add the $ref as another branch of the allOf and it will work.

That would look like:

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

Note: in the schema you posted, you have two unclosed strings "#/definitions/Oauth1 and "#/definitions/Oauth2. If you had that in your real schema it would be invalid JSON.



来源:https://stackoverflow.com/questions/55597775/is-it-possible-to-create-a-json-schema-with-allof-multiple-if-and-then-and-re

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!