farincz
farincz

Reputation: 5173

Restrict properties in json schema

Is there better solution for restricting property names then following?

{
    "type": "object",
    "not": {
        "anyOf": [{
           "required": ["a"]
        }, {
           "required": ["b"]
        }]
    }
}

I would like to accept any properties except a or b. Solution about works, but it's quite complicated and validation errors message in my python validator is odd.

Upvotes: 2

Views: 1498

Answers (2)

rayseaward
rayseaward

Reputation: 328

If you're interested in how to do this with patternProperties, you could do this:

{
    "type": "object",
    "patternProperties": {
        "[aA]": {
            "not": {}
        },
        "[bB]": {
            "not": {}
        }
}

I needed a similar solution to support the rejection of case insensitive property names. As of draft 4, the implementations I used don't support the regex pattern "/i" to ignore case.

Upvotes: 0

cloudfeet
cloudfeet

Reputation: 12863

Your solution is nice and readable. I can see how it produces odd validation errors (not always makes those complicated), but I would say the schema itself explains the constraints quite well.

You could do it a few bytes shorter using oneOf (e.g. {"oneOf": [{}, {"required": ["a"]}]}), but I don't think it's readable.

You could also do something horrible with patternProperties (i.e. make a regex that matched anything except "a"/"b" and then use additionalProperties), but again I think that's less readable.

I think the solution you have is good.

Upvotes: 1

Related Questions