对于下面给定的模式,是否可以确保至少一个属性包含一个值(即 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": "" 
} 

请您参考如下方法:

我会尝试类似的东西

{ 
    "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”模式中,所以至少其中一个应该匹配,加上原始模式。


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!