【问题标题】:How to make json-schema to allow one but not another field?如何使 json-schema 允许一个但不允许另一个字段?
【发布时间】:2013-10-17 20:26:36
【问题描述】:

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

例如,如果我想要一个 JSON 和 ether start_dtend_dt 的图像,但不能同时使用它们。像这样:

好的

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

我应该在架构中添加什么:

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

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

【问题讨论】:

    标签: python json jsonschema


    【解决方案1】:

    您可以使用oneOf 来表达这一点。这意味着数据必须与恰好匹配一个提供的子模式,但不能超过一个。

    将此与required 结合起来,此架构表示实例必须定义start_dt,或定义end_dt - 但如果它们同时包含两者,则无效:

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

    带有三个示例的在线演示:

    【讨论】:

    • cloudfeet:感谢您提供的信息。我在阅读文档时一定错过了这一点。今天学到了一些新东西
    • 是的,非常感谢您的澄清! IMO JSON模式规范中关于oneOf / allOf的部分不是很清楚,可能需要更多示例,例如这里
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-23
    • 1970-01-01
    • 2020-03-23
    • 2019-02-04
    • 1970-01-01
    • 2010-09-12
    相关资源
    最近更新 更多