允许属性为任何字符串

Allow Properties to be any string

给定以下 json 文档:

{
    "property-1": {
        "server": "string-value",
        "environment": "string-value",
        "cluster": "string-value"
    },
    "property-2": {
        "server": "string-value",
        "environment": "string-value",
        "cluster": "string-value"
    }
}

我正忙于为这种类型的 json 文档创建一个 json 模式,其中 property-1 可以是任何字符串,但在其中,我们将有一个集合结构一些必需的。我正在苦苦挣扎的是如何定义架构,以便用户能够为 property-1 | property-2.

设置任何字符串

我假设我必须使用一种模式,但我尝试过的方法效果不佳。

{
    "$schema": "http://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "definitions": {
        "role": {
            "$id": "#svcrole",
            "description": "Application name for which role is required.",
            "type": "object",
            "pattern": "^[a-zA-Z\-]+$",
            "properties": {
                "server": {
                    "type": "string"
                },
                "environment": {
                    "type": "string"
                },
                "cluster": {
                    "type": "string"
                }
            },
            "required": [
                "server",
                "environment",
                "cluster"
            ]
        }
    },
    "properties": {
        "$schema": {
            "type": "string"
        },
        "$name": {
            "$ref": "#/definitions/role"
        }
    }
}

所以我在这里偶然发现了解决方案。

您想像这样使用 propertyNamespatternProperties

"propertyNames": {
    "pattern": "^[a-zA-Z\-]+$"
},
"patternProperties": {
    "": {
        "$ref": "#/definitions/role"
    }
}

这将允许您使用模式来定义 属性 名称并使其全部动态化。