Json Schema Conditional if/Then not working

Viewed 158

I'm new to Json Schema validation. I think the validation should fail, but it passes. Not sure why the If/then is not forcing the required field. I believe I formatted the If/Then correctly.

JSON:

{
    "name": "Battery Wear",
    "triggerAlert": {
        "trigger": "When",
        "timeSpan": 50,
        "timeSpanMeasure": "Hours"
    }
}

SCHEMA:

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "type": "object",
    "required": [
        "name",
        "triggerAlert"
    ],
    "properties": {
        "name": {
            "type": "string"
        },
        "triggerAlert": {
            "type": "object",
            "required": ["trigger"],
            "properties": {
                "trigger": {
                    "type": "string",
                    "enum": ["Always","When"]
                },
                "numberOfEvents": {
                    "type": "integer"
                },
                "timeSpan": {
                    "type": "integer"
                },
                "timeSpanMeasure": {
                    "type": "string"
                }
            },
            "if": { "properties": {"trigger": {"enum": ["When"]} } },
            "then": {            
                "required": [
                    "numberOfEvents",
                    "timeSpan",
                    "timeSpanMeasure"
                ]
            }
        }
    }
}
1 Answers

Depending on the implementation you are using, you may not have support for these conditionals. if/then/else were only added in specification draft 7.

The schema is correct; the expected error result is:

{
  "errors" : [
    {
      "error" : "missing property: numberOfEvents",
      "instanceLocation" : "/triggerAlert",
      "keywordLocation" : "/properties/triggerAlert/then/required"
    },
    {
      "error" : "subschema is not valid",
      "instanceLocation" : "/triggerAlert",
      "keywordLocation" : "/properties/triggerAlert/then"
    },
    {
      "error" : "not all properties are valid",
      "instanceLocation" : "",
      "keywordLocation" : "/properties"
    }
  ],
  "valid" : false
}
Related