json-schema 中是否有一种方法可以验证与正则表达式匹配的对象键?
Is there a way in json-schema to validate object keys matching regex?
有没有办法让 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[]": 123
}
}
我尝试使用 patternProperties
,但任何与我的正则表达式不匹配的内容都会被忽略,不会在有问题的行上抛出验证错误。
这与 patternProperties 上的文档一致:
https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties
有没有办法做我正在寻找的东西?谢谢
您应该能够使用 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 模式验证器验证 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[]": 123
}
}
我尝试使用 patternProperties
,但任何与我的正则表达式不匹配的内容都会被忽略,不会在有问题的行上抛出验证错误。
这与 patternProperties 上的文档一致:
https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties
有没有办法做我正在寻找的东西?谢谢
您应该能够使用 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
}
}
}
}