首页 > 解决方案 > 是否需要在 AdditionalProperties 中添加dependentSchemas 属性

问题描述

我正在尝试编写一个模式,如果存在属性 A,那么属性 B 或 C 也应该使用依赖模式构造来存在,并且在我的模式中,我已经关闭了任何附加属性。

{
  "$schema": "https://json-schema.org/draft/2019-09/schema",
  "$id": "PropertiesSchema.json",
  "type": "object",
  "properties": {
    "A": { "type": "boolean" }
  },
  "additionalProperties": false,
  "dependentSchemas": {
    "A": {
      "anyOf": [
        { "required": [ "B" ] },
        { "required": [ "C" ] }
      ],
      "properties": {
        "B": { "type": "boolean" },
        "C": { "type": "boolean" }
      }
    }
  }
}

但由于 additionalProperties 构造,它目前在以下输入中失败

{“A”:真,“B”:假}或{“A”:真,“C”:假}

那么在 AdditionalProperties 关闭时是否允许dependentSchemas 属性?

因此有效的输入应该是

{“A”:真,“B”:假}或{“A”:真,“C”:假}

但是对于任何其他属性说D,它应该失败-

{“A”:真,“D”:假}

标签: jsonschemajson-schema-validator

解决方案


additionalProperties只能在相同的模式对象级别考虑properties(和)。patternProperties

如果您将其更改为,unevaluatedProperties您会发现它可以正常工作。

unevaluatedProperties可以“看穿”涂抹器关键字,例如dependentSchemas. 它必须等待其他关键字首先被解析,最后被解析。


推荐阅读