我正在尝试使用 JSON Schema 验证 JSON 文件,以查找“损坏的引用”的情况。基本上我的文件由项目和组组成,每个项目都属于由 groups 属性键引用的单个组,如下所示:
{
"items": {
"banana": {
"name": "Banana",
"group": "fruits"
},
"apple": {
"name": "Apple",
"group": "fruits"
},
"carrot": {
"name": "Carrot",
"group": "vegetables"
},
"potato": {
"name": "Potato",
"group": "vegetables"
},
"cheese": {
"name": "Cheese",
"group": "dairy"
}
},
"groups": {
"fruits": {
"name": "Fruits"
},
"vegetables": {
"name": "Vegetables"
}
}
}
在上面的示例中,项目
cheese
被视为无效,因为没有 dairy
属性(property)在groups
目的。我尝试使用以下模式验证这一点:{
"$schema": "http://json-schema.org/draft-06/schema#",
"title": "Food",
"id": "food",
"type": "object",
"properties": {
"items": {
"type": "object",
"patternProperties": {
"^[A-Za-z0-9-_.:=]+$": {
"properties": {
"name": {
"type": "string",
"pattern": "^[A-Za-z- ]+$"
},
"group": {
"pattern": "^[a-z]+$",
"enum": {
"$data": "/groups"
}
}
}
}
}
},
"groups": {
"type": "object",
"patternProperties": {
"^[A-Za-z0-9-_]+$": {
"properties": {
"name": {
"type": "string",
"pattern": "^[A-Za-z- ]+$"
}
}
}
}
}
},
"additionalProperties": false
}
这具有
enum
的效果为 group
由 groups
中的属性值填充,但我想要做的是使用 groups
中定义的属性键.如果我添加一个属性,例如
groupIds
并让它成为在 groups
中找到的所有属性键的数组并将枚举指定为 "$data": "/groupIds"
它确实有效,所以我认为这是一个 JSON 指针问题。enum
JSON Schema 中的关键字定义为:The value of this keyword MUST be an array. This array SHOULD have at least one element. Elements in the array SHOULD be unique.
所以如果我只能得到 JSON 指针来引用一个对象的键而不是它的值,我猜枚举验证就会起作用。我在想类似
"$data": "/groups/.keys"
, "$data": "/groups/$keys"
或类似的,但在谷歌搜索或阅读规范时没有找到它。有没有这样的事情,或者曾经有人提出过?
最佳答案
哪有这回事。它非常接近 JSON 中的通用表达式,它可能有一些用例,但没有这样的规范。
关于json - 使用对象属性键作为 JSON 模式中的枚举,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47454339/