json-schema 描述对象键的值(当键是动态的时)
json-schema describe object key's values (when keys are dynamic)
我有一个具有动态键名的对象,我想描述键可以具有的值架构,即:
{
"properties": {
"usersById": {
"additionalProperties": {
"properties": {
"email": {
"type": "boolean"
},
"phone": {
"type": "boolean"
},
"address": {
"type": "boolean"
}
},
"type": "object"
},
"type": "object"
}
},
...
}
这似乎在我的验证步骤中没有做任何事情(使用 AJV JS pkg)。我只想限制到这个模型模式:
{
usersById: {
'1234abcd': {
email: true,
phone: false,
address: false,
},
},
}
您可以使用 patternProperties
,这类似于 properties
,但您使用的是正则表达式。
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.5
一个例子...
架构:
{
"type": "object",
"patternProperties": {
"^S_": { "type": "string" },
"^I_": { "type": "integer" }
},
"additionalProperties": false
}
有效实例:
{ "I_0": 42 }
无效实例:
{ "S_0": 42 }
示例来自 https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties
请注意,请记住这些正则表达式不是隐式锚定的,因此如果您需要锚定的正则表达式,则需要锚定它们。
我有一个具有动态键名的对象,我想描述键可以具有的值架构,即:
{
"properties": {
"usersById": {
"additionalProperties": {
"properties": {
"email": {
"type": "boolean"
},
"phone": {
"type": "boolean"
},
"address": {
"type": "boolean"
}
},
"type": "object"
},
"type": "object"
}
},
...
}
这似乎在我的验证步骤中没有做任何事情(使用 AJV JS pkg)。我只想限制到这个模型模式:
{
usersById: {
'1234abcd': {
email: true,
phone: false,
address: false,
},
},
}
您可以使用 patternProperties
,这类似于 properties
,但您使用的是正则表达式。
https://datatracker.ietf.org/doc/html/draft-handrews-json-schema-validation-01#section-6.5.5
一个例子...
架构:
{
"type": "object",
"patternProperties": {
"^S_": { "type": "string" },
"^I_": { "type": "integer" }
},
"additionalProperties": false
}
有效实例:
{ "I_0": 42 }
无效实例:
{ "S_0": 42 }
示例来自 https://json-schema.org/understanding-json-schema/reference/object.html#pattern-properties
请注意,请记住这些正则表达式不是隐式锚定的,因此如果您需要锚定的正则表达式,则需要锚定它们。