简体   繁体   English

json-schema 中有没有办法验证匹配正则表达式的对象键?

[英]Is there a way in json-schema to validate object keys matching regex?

Is there a way to have the json schema validator to validate keys of a json object?有没有办法让 json 模式验证器来验证 json 对象的 For example:例如:

{
    "$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"
                }
            }
        }
    }
}

So here's some examples of what should and shouldn't pass:所以这里有一些应该和不应该通过的例子:

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

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

I tried using patternProperties but anything that doesn't match my regex is just ignored, no validation error is thrown on the offending line.我尝试使用patternProperties但任何与我的正则表达式不匹配的东西都被忽略了,没有在违规行上抛出验证错误。 This is consistent with documentation on patternProperties: https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties这与关于 patternProperties 的文档一致: https ://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties

Is there a way to do what i'm looking for?有没有办法做我正在寻找的东西? Thanks谢谢

You should be able to use additionalProperties to make an object invalid that doesn't pass the patternProperties you've required.您应该能够使用additionalProperties使不传递所需的patternProperties的对象无效。

By default any additional properties are allowed.默认情况下,允许任何其他属性。

{
"$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 JSON 模式:附加属性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM