jsonschema - json-schema 描述对象键的值(当键是动态的时)
问题描述
我有一个具有动态键名的对象,我想描述键可以具有的值模式,即:
{
"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
which is likeproperties
但您使用的是正则表达式。
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
请注意,最好记住这些正则表达式不是隐式锚定的,因此如果您需要锚定正则表达式,则需要锚定它们。
推荐阅读
- mysql - 加入两个加入?
- python - Anaconda Jupyter 没有被 cmd 和 Anaconda Navigator 打开
- spring-boot - 不允许使用不同通道的两个队列管理器
- reactjs - 如何测试作为道具开玩笑酶 ReactJS 传递的字符串
- google-cloud-platform - 如何在 Google Cloud Build 中使用 PNPM?
- apache-spark - 是否可以在火花中加入 TempView,因为它正在抛出无法解决符号错误
- javascript - 无法使用 express-unless 免除一些路由的身份验证
- c - 检查 docker alpine musl 版本
- java - 在 EditText 中键入时为文本添加下划线 - Android
- node.js - 无法创建反应应用,发现 1 个低严重性漏洞