小编典典

正确的JSON模式用于不同类型的项目数组

json

我有一个JSON项目的无序数组。根据规范http://tools.ietf.org/html/draft-zyp-json-
schema-03#section-5.5,下面的json模式仅在数组中的对象出现在那个顺序中时才会验证。我不想指定顺序,只验证数组中的对象,而不管对象的顺序或数量如何。从规范我似乎无法理解如何完成此工作。

"transactions" : {
    "type" : "array",
    "items" : [
        {
            "type" : "object",
            "properties" : {
                "type" : {
                    "type" : "string",
                    "enum" : ["BUILD", "REASSIGN"]
                }
            }
        },
        {
            "type" : "object",
            "properties" : {
                "type" : {
                    "type" : "string",
                    "enum" : ["BREAK"]
                }
            }
        }
    ]
}

阅读 229

收藏
2020-07-27

共1个答案

小编典典

我在JSON模式Google组上问了同样的问题,很快就得到了回答。fge用户要求我在此处发布他的回复:

你好,

当前规范是v4草案,而不是v3草案。更具体地说,验证规范在这里:

http://tools.ietf.org/html/draft-fge-json-schema-
validation-00

该网站不是最新的,我不知道为什么……我将提交拉取请求。

在草案v4中,您可以使用以下命令:

{
    "type": "array",
    "items": {
        "oneOf": [
            {"first": [ "schema", "here" ] }, 
            {"other": [ "schema": "here" ] }
        ]
    }  
}

例如,这是一个数组的架构,其中的项可以是字符串或整数(尽管可以用更简单的方式编写):

{
    "type": "array",
    "items": {
        "oneOf": [
            {"type": "string"},
            {"type": "integer"}
        ]
    }
}

这是正确的答案。我更正的架构现在包括:

"transactions" : {
    "type" : "array",
    "items" : {
        "oneOf" : [
            {
                "type" : "object",
                "properties" : {
                    "type" : {
                        "type" : "string",
                        "enum" : ["BUILD", "REASSIGN"]
                    }
                }
            },
            {
               "type" : "object",
               "properties" : {
                 "type" : {
                   "type" : "string",
                   "enum" : ["BREAK"]
                  }
               }
            }
        ]
    }
}
2020-07-27