基于Label值的JSON Schema数组对象匹配验证问题求助
解决方案
你需要针对数组中的每个元素单独设置条件验证,而非对整个数组做包含判断。核心思路是在props的items里用if/then关键字,为不同label值的对象指定专属验证规则:
{ "type": "object", "properties": { "props": { "type": "array", "items": { "type": "object", "properties": { "label": { "type": "string" }, "attributes": { "type": "object" } }, "required": ["label", "attributes"], // 验证Residential类型的对象 "if": { "properties": { "label": { "const": "Residential" } }, "required": ["label"] }, "then": { "properties": { "attributes": { "required": ["housingStatus"], "properties": { "housingStatus": { "const": "Own" } } } } }, // 验证Communication类型的对象 "if": { "properties": { "label": { "const": "Communication" } }, "required": ["label"] }, "then": { "properties": { "attributes": { "required": ["canContact"], "properties": { "canContact": { "const": "Yes" } } } } } } } }, "required": ["props"] }
关键细节
- 把条件逻辑放在
items内部,确保每个数组元素独立检查,不会误影响其他元素。 - 用
const精准匹配label值,比pattern更简洁高效。 - 每个
if/then块仅对对应label的对象生效,其他label的对象只要满足基础结构(含label和attributes字段)即可,不受特定规则约束。后续新增其他label的验证规则,直接加新的if/then块就行。
验证结果
- 若
label为Residential,必须包含attributes.housingStatus且值为Own,否则验证失败。 - 若
label为Communication,必须包含attributes.canContact且值为Yes,否则验证失败。
内容的提问来源于stack exchange,提问作者Nadeem
相关产品推荐
相关产品推荐

