如何使用JSON模式检查匹配属性?



我正在用Python制作一个Discord bot,它对消息中的某些关键字做出反应,我的脚本使用JSON文件,例如可能看起来像这样:

{
"characters": {
"john": {
"name": "Johnny",
"hex_colour": "0xC61B1B"
},
"marc": {
"name": "Marcus",
"hex_colour": "0x8AC0FF"
}
},
"reactions": [
{
"keywords": ["Hi", "Hello"],
"quotes": {
"john": ["Hello my name is Johnny"]
"marc": [
"Hi there. I'm Marcus.",
"Not now, I'm looking for John, have you seen him?"
]
}
},
{
"keywords": ["Bye"],
"quotes": {
"john": ["See you later!"]
}
}
]
}

正如你所看到的结构是相当复杂的,所以我决定为它做一个模式,这样vscode可以指出任何问题。它现在看起来像这样:

{
"title": "Quotes data",
"description": "Quotes bot data file",
"type": "object",
"properties": {
"characters": {
"title": "Character collection",
"description": "A collection of the available characters.",
"type": "object",
"additionalProperties":{
"title": "Character tag",
"description": "A tag that represents the character as a short string",
"type": "object",
"properties": {
"name": {
"title": "Character name",
"description": "The name of the character.",
"type": "string"
},
"hex_colour": {
"title": "Character colour",
"description": "The hex code of the colour in 0x000000 format.",
"type": "string"
},
"image_url": {
"title": "Character image",
"description": "An url to an image of the character.",
"type": "string"
}
},
"required": ["name"],
"additionalProperties": false
}
},
"reactions": {
"title": "Reaction collection",
"description": "A list of the reactions",
"type": "array",
"items": {
"type": "object",
"properties": {
"keywords": {
"title": "Keyword list",
"description": "A list of keywords for the bot to react to.",
"type": "array",
"items": {
"title": "Keyword",
"type": "string",
"minItems": 1,
"uniqueItems": true
}
},
"quotes": {
"title": "Quotes collection",
"description": "A collection of characters with quotes.",
"type": "object",
"additionalProperties":{
"title":"Character tag",
"description": "A tag that matches a character above.",
"type": "array",
"items": {
"title": "Quote",
"description": "A quote to react with.",
"type": "string",
"minItems": 1,
"uniqueItems": true
}
}
}
},
"required": ["keywords", "quotes"],
"additionalProperties": false
}
}
},
"required": ["characters", "reactions"],
"additionalProperties": true,
"allowTrailingCommas": true
}

对于字符的属性对象中允许使用任何属性名,因此我使用了& additionalProperties"之后,对于"引号"反对,我也这么做了。但在这种情况下,不应该允许任何财产。只匹配"字符"的属性之一。对象是允许的。是否有任何方法使模式检查匹配的属性?

这是一个非常具体的语义检查,使用JSON Schema的标准规范是不可能的。验证不能访问任意一组属性名,也不能查找验证路径。您需要将其添加为应用程序代码。

最新更新