对于下面给定的模式,是否可以确保至少有一个属性包含一个值(即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": "" }
erosb.. 10
我会尝试像
{ "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”模式中,因此至少其中一个应匹配,再加上原始模式。
我会尝试像
{ "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”模式中,因此至少其中一个应匹配,再加上原始模式。
是否要求允许值为空?如果要求所有字符串都是非空的,则可以编写更清晰的模式.
{ "$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 }, } }