【问题标题】:Is there a way in json-schema to validate object keys matching regex?json-schema 中有没有办法验证匹配正则表达式的对象键?
【发布时间】:2021-10-06 06:43:36
【问题描述】:

有没有办法让 json 模式验证器来验证 json 对象的 keys?例如:

{
    "$schema": "http://json-schema.org/draft-07/schema",
    "type": "object",
    "properties": { // here properties is an object containing user-defined keys that should be alphanumeric or underscore.
        "values": {
            "type": "object",
            "patternProperties": {
                "[a-zA-Z0-9_]+": {
                    "description": "Foo"
                }
            }
        }
    }
}

下面是一些应该和不应该通过的示例:

// Should pass:
{
 "values": {
   "myKey1": { "foo": 1 },
   "myKey2_": "bar"
 }
}

// Should fail but no error is shown saying this doesnt match schema:
{
  "values": {
    "m\1[]": 123
  }
}

我尝试使用patternProperties,但任何与我的正则表达式不匹配的内容都会被忽略,在违规行上不会引发验证错误。 这与 patternProperties 上的文档一致: https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties

有没有办法做我正在寻找的东西?谢谢

【问题讨论】:

    标签: javascript json regex jsonschema json-schema-validator


    【解决方案1】:

    您应该能够使用additionalProperties 使未通过您所需的patternProperties 的对象无效。

    默认情况下允许任何其他属性。

    {
    "$schema": "http://json-schema.org/draft-07/schema",
    "type": "object",
    "properties": {
        "values": {
            "type": "object",
            "patternProperties": {
                "[a-zA-Z0-9_]+": {
                    "description": "Foo"
                },
                "additionalProperties": false
                }
            }
        }
    }
    

    JSON Schema : Additional Properties

    【讨论】:

    • 感谢您的帮助。那行得通。后续问题是如何添加一些自定义验证消息,例如“此名称不是字母数字和下划线格式”?
    • @joeb。不客气!关于自定义消息; json 真的没有这样做。它通常是无效的或有效的。查看文档的required 部分(在该页面上已有的信息下方)~欢呼!
    猜你喜欢
    • 2020-07-18
    • 2019-02-11
    • 2015-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多