首页 > 解决方案 > JSON 模式定义集合中元素的单一用途

问题描述

我使用draft-04来定义 JSON 模式。我最初的问题是我想为下面的结构定义模式

{
"config1" : [
              { <category-1> : {some Object which i know how to define schema} },
              { <category-2> : {some Object which i know how to define schema} }
            ],
"config2" : {some other structure}
}

这里 category-n 是在包含类别的 n 元素集合中定义的类别。
我知道架构定义了一个静态数据结构,因此我们无法枚举键(正确吗?)所以作为一种解决方法,我需要如下配置

"config1" : [
              { "categoryName" : "category-1"
                "categoryPayload" : {some Object which i know how to define schema} },
              { "categoryName" : "category-2"
                "categoryPayload" : {some Object which i know how to define schema} }
            ]

对于每个类别定义,我知道我可以像"enum": ["category-1", "category-1"]使用,但问题是,在第一个 json 中,我从不使用重复键的 json 建议中受益。每个类别都是独一无二的,我不希望有人对同一类别使用不同的 categoryPayload。如何将 config-1 的数组元素限制为每个类别只有 1 个元素(没有重复的类别元素)

编辑-1

以我的派生方法为例(使用类别作为值而不是键),假设类别 1、类别 2 和类别 3 是允许的类别。因此下面的 json 应该通过验证

{
  "config-1": [
    {
      "categoryName": "category-1",  //line-1
      "categoryPayload": {
        "key1": "value1",
        "key2": "value2"
      }
    },
    {
      "categoryName": "category-2",   //line-2
      "categoryPayload": {
        "key1": "value1",
        "key3": "value3"
      }
    }
  ],
  "config-2": "something"
}

如果将第 1 行替换为第 2 类(第 1 行和第 2 行具有相同的值),这应该会导致验证失败。显然,如果我在第 1 行替换第 7 类(不是允许的枚举的一部分),它也应该无法通过验证。

标签: jsonjsonschemajson-schema-validator

解决方案


每个类别的架构永远不会相同吗?您不能断言对象值的唯一性,而是其模式的唯一性。

{
    "type": "object",
    "properties": {
      "config1": {
        "type": "array",
        "items": {
          "type": "object",
          "patternProperties": {
            "\\w+": {
              "oneOf": [
                {"type": "object", "properties": {"a": {}}, "additionalProperties": false},
                {"type": "object", "properties": {"b": {}}, "additionalProperties": false}
              ]
            }
          },
          "additionalProperties": false
        }
      }
    }
}

更新:这是另一种方式:

{
    "type": "object",
    "properties": {
      "config1": {
        "type": "array",
        "items": [
          {"type": "array", "items": {"type": "string"}, "uniqueItems": true},
          {"type": "array", "items": {"type": "object"}, "uniqueItems": true},
        ]
      }
    }
}

这样您就可以拥有唯一的键和值。然后在应用程序中压缩两个数组。

这是通过的:

{
  "config1" : [
    ["category-1", "category-2"],
    [{"a": 1}, {"a": 2}]
  ]
}

这是失败的:

{
  "config1" : [
    ["category-1", "category-2"],
    [{"a": 1}, {"a": 1}]
  ]
}

推荐阅读