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

2020-02-22 07:35发布

Is it possible to set up a JSON schema that still allows for additionalProperties but does not match if a very particular property name is present? In other words, I need to know if it's possible to have the exact opposite of the required declaration.

Schema:

{
    "type": "object",
    "properties": {
        "x": { "type": "integer" }
    },
    "required": [ "x" ],
    "ban": [ "z" ] // possible?
}

Match:

{ "x": 123 }

Match:

{ "x": 123, "y": 456 }

Do not match:

{ "x": 123, "y": 456, "z": 789 }

4条回答
时光不老,我们不散
2楼-- · 2020-02-22 08:17

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" : {}

        }
    }
}
查看更多
Emotional °昔
3楼-- · 2020-02-22 08:30

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
}
查看更多
太酷不给撩
4楼-- · 2020-02-22 08:32

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" ]
}
查看更多
男人必须洒脱
5楼-- · 2020-02-22 08:36

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" ] }
}
查看更多
登录 后发表回答