如何使json模式允许一个但不允许另一个字段? [英] How to make json-schema to allow one but not another field?

查看:94
本文介绍了如何使json模式允许一个但不允许另一个字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以使jsonschema仅具有两个字段之一.

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

例如,如果我想让一个带有醚start_dtend_dtJSON而不是两个都同时使用,则为image.像这样:

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:

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

确定

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

不好

{
    "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"
            }
    }
}

推荐答案

您可以使用oneOf表示.这意味着数据必须与提供的子方案中的完全匹配,但不得超过一个.

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.

将此与required结合使用,该架构表示实例必须定义start_dt或定义end_dt-但是如果它们都包含,则无效:

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

这篇关于如何使json模式允许一个但不允许另一个字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆