How to apply constraint on the basis of count of properties?

33 Views Asked by At

I am trying to write a schema that will validate json of this type

{
    "Steps": {
        "0": {
            "something": "something"
        },
        "1": {
            "something": "something"
        }
    }
}

with constraints: 1: Steps can be empty ie {"Steps":{}} is ok 2: Key values can be 0 to 99. 3: if Steps is not empty, it must have key 0 in it.

I have used patternProperties to apply the constraint on key names (constraint 2)

{
    "Steps": {
        "patternProperties": {
            "^[0-9]$|^[1-9][0-9]$": {
                "type": "object",
                "$ref": "#/$defs/StepDetails"
            }
        },
        "additionalProperties": false
    }
}

But I dont know how to apply the constraint number 3 above. I don't want to make property "0" required unconditionally because that will interfere with my constraint number 1 so how can I specify that "if count of properties in Steps >0, property "0" is required"

Thanks,

minProperties and maxProperties are not useful here I guess.

1

There are 1 best solutions below

1
Girish Tharwani On

This seems to work but I was hoping for a more elegant if-then type of solution

{
"Steps": {
    "patternProperties": {
        "^[0-9]$|^[1-9][0-9]$": {
            "type": "object",
            "$ref": "#/$defs/StepDetails"
        }
    },
    "additionalProperties": false,
    "anyOf": [
        {
            "required": [
                "0"
            ]
        },
        {
            "maxProperties": 0
        }
    ]
}

}