JSON Schema oneOf properies filled

2020-08-12 06:07发布

问题:

How to set JSON Schema rule to say that exactly one of the properties have to be set and is required?

I tried various ways to solve it like:

{
   "id":"#",
   "required":true,
   "additionalProperties":true,
   "type":"object",
   "properties":{
      "surname":{
         "id":"surname",
         "required":true,
         "type":"string"
      },
      "oneOf":[
         {
            "$ref":"#/definitions/station_id"
         },
         {
            "$ref":"#/definitions/station"
         }
      ]
   },
   "definitions":{
      "station_id":{
         "type":"integer"
      },
      "station":{
         "type":"string"
      }
   }
}

But it never worked. What I need to do is to accept either station_id what is an integer or station what is a string name.

Is there a way to do that, please?

回答1:

oneOf is only special when used directly inside a schema. When you use oneOf inside properties, then it has no special meaning, so you actually end up defining a property called "oneOf" instead.

Also - it's not the property definitions that make something required, it's the required keyword. This keyword is an array of required properties (not a boolean, that's old syntax).

To do what you want, you make a oneOf clause where one option has "station_id" required, and the other has "station" required:

{
    "oneOf": [
        {"required": ["station"]},
        {"required": ["station_id"]}
    ]
}

If both are present, then the data will be invalid (because only one oneOf entry is allowed to pass).