我正在尝试使用JSON Schema创建一个结构,允许我定义一个包含枚举值(options.json
)的键值对象,还有一个用于验证某个查询的查询模式( query.json
)。为了防止代码重复,我正在寻找一种方法,只允许我的查询模式中的键是我的其他模式中定义的键。最令人讨厌的部分是,当我查询时,我可能想要“value1”和“value2”匹配。所以我想要实现的是,我的查询只在options.json
中将键定义为属性,但它应该接受value1
作为值或["value1", "value2"]
作为值。
// options.json
{
"id": "options.json",
"type": "object",
"properties": {
"option1": {
"type": "string",
"enum": [
"value1",
"value2",
"value3"
]
},
"option2": {
"type": "string",
"enum": [
"value4",
"value5",
"value6"
]
}
},
"required": []
}
现在有一些样本数据:
// should be marked as valid
{
"option1": "value1"
}
// this as well
{
"option1": ["value1", "value2"]
}
// combination of the two also valid
{
"option1": "value1",
"option2": ["value5", "value6"]
}
// but this shouldn't
{
"option3": "doesn't exist"
}
我如何实现这样的结构?
我能得到的最接近的东西是这样的,但它仍然意味着我必须手动定义选项中指定的每个键:
{
"properties": {
"option1": {
"anyOf": [
{
"$ref": "options.json#/properties/option1"
},
{
"type": "array",
"items": {
"$ref": "options.json#/properties/option1",
"uniqueItems": true
}
}
]
}
}
}