JSON Schema oneOf properies filled

雨燕双飞 提交于 2019-12-22 03:16:33

问题


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).



来源:https://stackoverflow.com/questions/21565893/json-schema-oneof-properies-filled

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!