Json Schema - 定义不同对象中的属性之间的 dependentRequired

问题描述 投票:0回答:1

如何使用

dependantRequired
绑定不同对象中的两个属性?

例如在以下架构中:

{
    "$schema": "https://json-schema.org/draft/2019-09/schema",
    "$id": "https://test.com/account",
    "$vocabulary": {
        "https://json-schema.org/draft/2019-09/vocab/core": true,
        "https://json-schema.org/draft/2019-09/vocab/applicator": true,
        "https://json-schema.org/draft/2019-09/vocab/validation": true,
        "https://json-schema.org/draft/2019-09/vocab/meta-data": true,
        "https://json-schema.org/draft/2019-09/vocab/format": false,
        "https://json-schema.org/draft/2019-09/vocab/content": true
    },
    "$recursiveAnchor": true,
    "title": "Core and Validation specifications meta-schema",
    "properties": {
      "bearer": {
                  "$anchor": "bearer_anchor",
                    "type": "string"
                },
        "profile": {
            "type": "object",
            "properties": {
                "email": {
                  "type":"string"
                },
                "password": {
                  "type":"string"
                },
                "number": {
                    "type": "number"
                },
                "street_name": {
                    "type": "string"
                },
                "street_type": {
                    "enum": [
                        "Street",
                        "Avenue",
                        "Boulevard"
                    ]
                }
            },
            "dependentRequired": {
                "email": [{"$ref": "https://test.com/account#bearer_anchor"}],
                "password": [{"$ref": "https://test.com/account#bearer_anchor"}],
            }, 
            "additionalProperties": false
        }
    },
    "additionalProperties": false
}

我试图定义

profile\email
profile\password
必须与属性
bearer
一起提供。

我确实尝试了很多方法来使用 $ref 作为绝对路径,如你所见。

jsonschema json-schema-validator
1个回答
2
投票

您将无法使用

dependentRequired
来实现此目的,因为该关键字仅在同一架构中有效。但是,您可以使用
if
/
then

这个,

"dependentRequired": {
  "a": ["b"]
}

是模式的有效语法糖,

"if": { "required": ["a"] },
"then": { "required": ["b"] }

这比较冗长,但可以提供更多的表达能力。我们可以扩展它来检查

profile/email
属性。

"if": {
  "properties": {
    "profile": { "required": ["email"] }
  }
  "required": ["profile"]
},
"then": { "required": ["bearer"] }
© www.soinside.com 2019 - 2024. All rights reserved.