How to make json-schema to allow one but not another field?

我们两清 提交于 2019-12-06 03:02:47

问题


Is it possible to make jsonschema to have only one of two fields.

For example, image if I want to have a JSON with ether start_dt or end_dt but not both of them at the same time. like this:

OK

{
    "name": "foo",
    "start_dt": "2012-10-10"
} 

OK

{
    "name": "foo",
    "end_dt": "2012-10-10"
} 

NOT OK

{
    "name": "foo",
    "start_dt": "2012-10-10"
    "end_dt": "2013-11-11"
} 

What should I add to the schema:

{ 
    "title": "Request Schema",
    "type": "object",
    "properties": {
        "name": 
            {   
                "type": "string"
            },  
        "start_dt": 
            {
                "type": "string",
                "format": "date"

            },
        "end_dt":
            {
                "type": "string",
                "format": "date"
            }
    }
}

回答1:


You can express this using oneOf. This means that the data must match exactly one of the supplied sub-schemas, but not more than one.

Combining this with required, this schema says that instances must either define start_dt, OR define end_dt - but if they contain both, then it is invalid:

{
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "start_dt": {"type": "string", "format": "date"},
        "end_dt": {"type": "string", "format": "date"}
    },
    "oneOf": [
        {"required": ["start_dt"]},
        {"required": ["end_dt"]}
    ]
}

Online demos with your three examples:

  • OK
  • OK
  • NOT OK


来源:https://stackoverflow.com/questions/19436589/how-to-make-json-schema-to-allow-one-but-not-another-field

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