【问题标题】:How do I set additionalProperties to false when using an array?使用数组时如何将 additionalProperties 设置为 false?
【发布时间】:2021-12-01 21:54:57
【问题描述】:

正在验证的文件如下所示:

MyArray:
  - someItemWithRandomName:
    one: f9jfw9j302
    two: 09dj0293jff
    three: 09dj0293jff
  - someOtherItemWithRandomName:
    one: f9jfw9j302
    two: 09dj0293jff
    three: 09dj0293jff
  - anotherItem:
    one: f9jfw9j302
    two: 09dj0293jff
    three: 09dj0293jff

我正在这样验证它:

"MyArray": {
  "type": "array",
  "items": {
    "type": "object",
    "additionalProperties": false,
    "required": [
      "one",
      "two",
      "three"
    ],
    "properties": {
      "one": {
          "type": "string"
      },
      "two": {
          "type": "string"
      },
      "three": {
          "type": "string"
      }
    }
  }

我不想允许未在架构中定义的数组项中的字段,但 "additionalProperties": false 不起作用,因为数组项的键可以是任何字符串。你如何适应这个?

编辑

这是我验证的一个活生生的例子。在验证之前,我假设的 YAML 将像本示例中一样转换为 JSON:https://www.jsonschemavalidator.net/s/PBmLkkBl

【问题讨论】:

  • 根据您的描述,您所拥有的应该可以工作。您能否发布一个当前不应该通过的数据示例?

标签: jsonschema


【解决方案1】:

您的架构中缺少一个级别,以允许将数组项的对象属性命名为任何名称。

试试这个:

"MyArray": {
  "type": "array",
  "items": {
    "type": "object",
    "additionalProperties": {
      "type": "object",
      "additionalProperties": false,
      "required": [
        "one",
        "two",
        "three"
      ],
      "properties": {
        "one": {
          "type": "string"
        },
        "two": {
          "type": "string"
        },
        "three": {
          "type": "string"
        }
      }
    }
  }

如果您想对在该中间层使用的名称进行限制,可以将“additionalProperties”替换为“patternProperties”:

...
"patternProperties": {
  "^[0-9]$": {
    ...
  }
}

或者,如果您想为属性名称使用架构,您可以使用“propertyNames”。

https://json-schema.org/understanding-json-schema/reference/object.html

【讨论】:

【解决方案2】:

(代表问题作者发布解决方案,将其移至答案空间)。

我的解决方案是删除数组的空项,因为它们没有被使用。我认为正确处理此问题的唯一方法是进行某种条件验证以允许所有属性为空值 - 如果这可能的话。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-08
    • 2012-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多