首页 > 解决方案 > 如何添加正则表达式以验证 JSON 模式中对象的键

问题描述

我想更改我的架构,以便任何以开头的属性com.xxx.都无效。

我如何实现它?在哪里定位正则表达式?你能给我一个例子吗?

   {
        "com.xxx.myapp": "xxx"
    }


{
    "$schema": "http://json-schema.org/draft-07/schema",
    "$id": "http://example.com/example.json",
    "type": "object",
    "title": "The root schema",
    "description": "The root schema comprises the entire JSON document.",
    "default": {},
    "examples": [
        {
            "com.xxx.myapp": "xxx"
        }
    ],
    "required": [
        "com.xxx.myapp"
    ],
    "properties": {
        "com.xxx.myapp": {
            "$id": "#/properties/com.xxx.myapp",
            "type": "string",
            "title": "The com.xxx.myapp schema",
            "description": "An explanation about the purpose of this instance.",
            "default": "",
            "examples": [
                "xxx"
            ]
        }
    },
    "additionalProperties": true
}

标签: jsonjsonschema

解决方案


您想使用patternProperties关键字。就像properties,但键是非锚定正则表达式。

“patternProperties”的值必须是一个对象。 根据ECMA 262 正则表达式方言,该对象的每个属性
名称都应该是一个有效的正则表达式。
此对象的每个属性值
必须是有效的 JSON 模式。

此关键字确定子实例如何验证对象,而不直接验证直接实例本身。针对此关键字验证原始实例类型始终成功。


如果对于在此关键字的值中显示为属性名称的任何正则表达式匹配的每个实例名称,该名称
的子实例成功地针对与匹配的正则 表达式
对应的每个模式进行验证,则验证成功。

https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.5


推荐阅读