JSON模式-仅允许现有键作为另一个对象中的值
假设我有以下JSON对象:JSON模式-仅允许现有键作为另一个对象中的值,json,jsonschema,Json,Jsonschema,假设我有以下JSON对象: { "firstKey": { "innerKey": null }, "secondKey": { "innerKey": null }, "thirdKey": { "innerKey": "firstKey" } } 通过使用JSON模式,我如何确保innerKey只能是firstKey或secondKey或null(即,我如何只允许来自其他对象的现有键作为值)?正
{
"firstKey": {
"innerKey": null
},
"secondKey": {
"innerKey": null
},
"thirdKey": {
"innerKey": "firstKey"
}
}
通过使用JSON模式,我如何确保
innerKey
只能是firstKey
或secondKey
或null
(即,我如何只允许来自其他对象的现有键作为值)?正如@Clemens所说的那样,这通常是不可能的。但是,如果您的JSON输入具有有限的数量以及定义良好的属性,那么您可以尝试这样的方法
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstKey": {
"properties": {
"innerKey": {
"allOf": [
{
"$ref": "#/definitions/innerKey"
},
{
"not": {
"const": "firstKey"
}
}
]
}
}
},
"secondKey": {
"properties": {
"innerKey": {
"allOf": [
{
"$ref": "#/definitions/innerKey"
},
{
"not": {
"const": "secondKey"
}
}
]
}
}
},
"thirdKey": {
"properties": {
"innerKey": {
"allOf": [
{
"$ref": "#/definitions/innerKey"
},
{
"not": {
"const": "thirdKey"
}
}
]
}
}
}
},
"definitions": {
"innerKey": {
"oneOf": [
{
"enum": [
"firstKey",
"secondKey",
"thirdKey"
]
},
{
"type": "null"
}
]
}
}
}
正如@Clemens所说,这通常是不可能的。但是,如果您的JSON输入具有有限的数量以及定义良好的属性,那么您可以尝试这样的方法
{
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"firstKey": {
"properties": {
"innerKey": {
"allOf": [
{
"$ref": "#/definitions/innerKey"
},
{
"not": {
"const": "firstKey"
}
}
]
}
}
},
"secondKey": {
"properties": {
"innerKey": {
"allOf": [
{
"$ref": "#/definitions/innerKey"
},
{
"not": {
"const": "secondKey"
}
}
]
}
}
},
"thirdKey": {
"properties": {
"innerKey": {
"allOf": [
{
"$ref": "#/definitions/innerKey"
},
{
"not": {
"const": "thirdKey"
}
}
]
}
}
}
},
"definitions": {
"innerKey": {
"oneOf": [
{
"enum": [
"firstKey",
"secondKey",
"thirdKey"
]
},
{
"type": "null"
}
]
}
}
}
对于当前版本的JSON模式,这是不可能的。您需要在一个单独的验证步骤中进行检查。这可能不是您想要实现的,但您可以定义一个枚举,因此innerKey只能是[“firsKey”、“secondKey”、null]中的一个。但是这个枚举应该通过指定键来构建,这在当前版本的JSON模式中是不可能的。您需要在一个单独的验证步骤中进行检查。这可能不是您想要实现的,但您可以定义一个枚举,因此innerKey只能是[“firsKey”、“secondKey”、null]中的一个。但是这个枚举应该通过指定键来构建。