对于下面给定的模式,是否可以确保至少有一个属性包含一个值(即minLength为1):
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"fundRaiseId": {
"type": "string"
},
"productTypeId": {
"type": "string"
},
"businessLineId": {
"type": "string"
}
}
}
所以这会通过验证:
{
"fundRaiseId": "x"
}
这会因为没有值而失败:
{
"fundRaiseId": "",
"productTypeId": "",
"businessLineId": ""
}
答案 0 :(得分:8)
是否要求允许值为空?如果要求所有字符串都是非空的,则可以编写更清晰的模式。
{
"$schema": "http://json-schema.org/draft-04/schema#",
"type": "object",
"properties": {
"fundRaiseId": { "$ref": "#/definitions/non-empty-string" },
"productTypeId": { "$ref": "#/definitions/non-empty-string" },
"businessLineId": { "$ref": "#/definitions/non-empty-string" }
},
"anyOf": [
{ "required": ["fundRaiseId"] },
{ "required": ["productTypeId"] },
{ "required": ["businessLineId"] }
],
"definitions": {
"non-empty-string": {
"type": "string",
"minLength": 1
},
}
}
答案 1 :(得分:6)
我会尝试像
这样的东西{
"allOf": [{
"type": "object",
"properties": {
"fundRaiseId": {
"type": "string"
},
"productTypeId": {
"type": "string"
},
"businessLineId": {
"type": "string"
}
}
}, {
"anyOf": [{
"properties": {
"fundRaiseId": {
"$ref": "#/definitions/nonEmptyString"
}
}
}, {
"properties": {
"productTypeId": {
"$ref": "#/definitions/nonEmptyString"
}
}
}, {
"properties": {
"businessLineId": {
"$ref": "#/definitions/nonEmptyString"
}
}
}]
}],
"definitions": {
"nonEmptyString": {
"type": "string",
"minLength": 1
}
}
}
说明:要验证的JSON应符合2个根级模式,一个是您的原始定义(3个字符串属性)。另一个包含3个额外的子模式,每个子模式将一个原始属性定义为非空字符串。它们包含在" anyOf"架构,因此至少有一个应该匹配,加上原始架构。