JSON schema - valid if object does *not* contain a particular property

会有一股神秘感。 提交于 2019-11-25 15:17:57

What you want to do can be achieved using the not keyword. If the not schema validates, the parent schema will not validate.

{
    "type": "object",
    "properties": {
        "x": { "type": "integer" }
    },
    "required": [ "x" ],
    "not": { "required": [ "z" ] }
}

There is a simpler approach. Define that if x is present it must not satisfy any schema. By reduction to absurdity x can not be present:

{
    "properties" : {
        "x" : {
            "not" : {}

        }
    }
}

I solved the issue by banning additional properties via "additionalProperties": false but using patternProperties to allow any property name except the banned one.

{
    "type": "object",
    "properties": {
        "x": { "type": "integer" }
    },
    "required": [ "x" ],
    "patternProperties": {
        "^(?!^z$).*": {}
    },
    "additionalProperties": false
}

To specify the absence of a field, you can expect it's type to be null.

{
    "type": "object",
    "properties": {
        "x": { "type": "integer" },
        "z": { "type": "null" }

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