首页 > 解决方案 > 我可以使用 if/then 来强制执行与先前给出的相矛盾的属性约束吗?

问题描述

我正在使用多部分 JSON 模式(但对 JSON 模式很陌生)。模式对包含资源模板的配置文件施加约束,每个资源模板都包含属性模板。我正在尝试更改对任何给定属性模板中的属性强制执行约束的方式。

属性模板的模式模块中,约束被放置在属性"mandatory"、、"repeatable"和上"type",如下所示:

"mandatory": {
  "type": ["boolean", "string"],
  "enum": ["true", "false"],
  "title": "Mandatory",
  "description": "Indication that a value for the property is required. If unspecified, defaults to false.",
  "default": false
},

[...]

"repeatable": {
  "type": ["boolean","string"],
  "enum": ["true", "false"],
  "title": "Repeatable",
  "description": "Indication that the property is repeatable. If unspecified, defaults to true.",
  "default": true
},

[...]

"type": {
  "type": "string",
  "enum": ["literal", "lookup", "resource"],
  "title": "Type",
  "description": "Type of value (literal / resource / lookup) that is allowed by this property."
},

我想使用 if then 语句来指示如果另一个属性的值是-1(指示属性模板已添加到配置文件但尚未填充值),它不需要符合规则以上。事实上,在这种情况下,我想确保上述属性的值是空字符串。

我尝试通过以下方式执行此操作:

"allOf": [

(这里有一些其他的if-thens)

    {
        "if": {
            "properties": {
                "uwFormOrder": {
                    "const": -1
                }
            }
        },
        "then": {
            "$ref": "#/definitions/empty-PTs"
        }
    }
 ],
 "definitions": {

(这里的一些其他定义)

"empty-PTs": {
      "properties": {
        "mandatory": {
          "const": ""
        },
        "repeatable": {
          "const": ""
        },
        "type": {
          "const": ""
        }
      }
    }

这种方法*根本上是错误的吗?

*这种方法=在现有的内部添加一个额外的 if/then "allOf",在现有的"definitions".

最后一点:我正在修改在这里公开发布的模式——原始作品不是我自己的,我只是试图在它的基础上构建一点。

标签: jsonjsonschema

解决方案


简而言之,JSON Schema 验证关键字为您的验证检查添加了约束。您以后无法删除它们。

相反,您必须构造if/then/else块以形成您想要的结果。

从您链接到的模式的外观来看,您似乎已经了解如何if/then/else正确使用。

请注意,您可以嵌套if/then/else块。每个关键字的值必须是 JSON Schema,它本身可以使用这些关键字。生成的嵌套thenelse模式将“冒泡”应用链以应用于其预期的位置。

从本质上讲,没有关键字可以忽略其他使用的关键字。


推荐阅读