Home > Software engineering >  JSON Schema Conditional Required - If not null & has certain value
JSON Schema Conditional Required - If not null & has certain value

Time:06-08

I have a pretty simple requirement:

If vehicleType IS NOT NULL, AND vehicleType IS CAR then topSpeed is required, else, topSpeed is not required.

Currently, if vehicleType (which is optional), is not provided, must have required property 'topSpeed' error is happening.

Any ideas what is wrong?

Here is a snippet of the JSON Schema:

"vehicle": {
    "type": "object",
    "properties": {
      "valuation": {
        "type": "number"
      },
      "vehicleType": {
        "type": "string",
        "enum": ["Car", "Airplane", "Boat", "Motorcycle", "Truck"]
      },
      "topSpeed": {
        "type": "number"
      }
    },

    "if": {
      "properties": {
        "vehicleType": {
          "const": "Car"
        }
      }
    },
    "then": {
      "required": ["topSpeed"]
    }
  }

CodePudding user response:

The if schema is true because vehicleType is not required. Therefore the then branch is applied even if vehicleType is not present. Add "required": [ "vehicleType" ] to the if schema.

enter image description here

  • Related