【问题标题】:json schema validate all array items against one or another schemajson 模式根据一个或另一个模式验证所有数组项
【发布时间】:2014-08-03 19:56:58
【问题描述】:

给定以下架构:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "definitions": {
        "worktype": {
            "blue": {
                "enum": [1, 2, 3]
            },
            "red": {
                "enum": [4, 5, 6]
            }
        }
    }
}

我可以验证一个数组是否由所有“蓝色”项目或“红色”项目组成,如下所示:

{
                "type": "array",
                "items": {
                    "$ref": "#/definitions/worktype/red"    // or worktype/blue
                }
}

但是如何验证一个数组只有“蓝色”或“红色”工作类型,而不是混合工作类型?

例如:

[1, 2]: Valid (only blue)
[5]: Valid (only red)
[1, 6]: Invalid (mixed blue and red)

我的第一个想法是使用oneOf

{
                "type": "array",
                "items": {
                    "oneOf": [
                        {"$ref": "#/definitions/worktype/red"},
                        {"$ref": "#/definitions/worktype/blue"},
                    ]
                }
}

但这会根据模式检查每个条目本身,因此例如[1, 6] 也是有效的。 (Afaik 在这种情况下,oneOf 并不意味着“所有项必须对 oneOf together有效”而是“每个项必须有效反对 oneOf 为自己”)。

如何为只有“蓝色”或“红色”工作类型但不是两者都有的数组编写架构?这可能吗?

【问题讨论】:

    标签: arrays json jsonschema


    【解决方案1】:

    我明白了,我的第一个想法是正确的,但是 oneOf 只是嵌套了一层太深。这就像我想要的那样工作:

    {
                    "type": "array",
                    "oneOf": [
                        {
                            "items": {
                                "$ref": "#/definitions/worktype/red"
                            }   
                        },  
                        {
                            "items": {
                                "$ref": "#/definitions/worktype/blue"
                            }   
                        }   
                    ]
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      相关资源
      最近更新 更多