JSON Schema required属性验证问题:内部必填字段未触发校验
修复JSON Schema中
accounts内部必填字段不校验的问题 我帮你拆解下问题根源,你这是Schema的结构不符合JSON Schema规范导致内部规则没被触发,调整后就能正常校验了:
问题核心错误分析
你的Schema里accounts字段的定义有两个关键问题:
- 缺少对象类型声明:JSON Schema需要明确指定
accounts是object类型,否则验证器无法识别这是一个需要校验内部结构的对象,自然会跳过它的required和properties规则。 required格式错误:required关键字必须接收字符串数组(比如["account"]),你写成了单个字符串"account",这不符合Draft-04的规范,验证器会直接忽略这个错误配置。
修复后的完整Schema
{ "$schema": "http://json-schema.org/draft-04/schema#", "required": [ "accounts" ], "properties": { "accounts": { "type": "object", "required": [ "account" ], "properties": { "account": { "type": "array", "minItems": 1, "maxItems": 999, "items": { "type": "object", "required": [ "scheme", "accountType", "accountSubType" ], "properties": { "scheme": { "description": "scheme", "type": "object", "required": [ "schemeName", "identification" ], "properties": { "schemeName": { "type": "string", "maxLength": 40 }, "identification": { "type": "string", "maxLength": 256 }, "name": { "type": "string", "maxLength": 70 }, "secondaryIdentification": { "type": "string", "maxLength": 35 } } }, "currency": { "type": "string", "format": "iso-4217", "pattern": "^[A-Z]{3}$", "maxLength": 3, "example": "EUR" }, "accountType": { "type": "string" }, "accountSubType": { "type": "string", "maxLength": 35 } } } } } } } }
关键调整说明
- 给顶层添加了
properties字段,把accounts的定义移入其中(这是JSON Schema的标准结构:先声明顶层必填字段,再在properties里定义每个字段的具体规则)。 - 为
accounts添加type: "object",明确它是对象类型。 - 把
accounts内的required: "account"修正为required: ["account"],符合数组格式要求。 - 顺便修复了原Schema里
schemeName后多余的语法逗号,以及把pattern中的{3,3}简化为{3}(功能完全一致,更简洁)。
验证效果
现在用{ "accounts": {} }测试,会得到预期的错误提示:
Required properties are missing from object: account. Schema path: #/properties/accounts/required
内容的提问来源于stack exchange,提问作者Vivek
相关产品推荐
相关产品推荐

