实现order_type为ORDER时必填items的JSON Schema条件校验咨询
修正JSON Schema实现条件校验需求
要实现「仅当attributes.order_type为"ORDER"时,必须包含items字段;其他order_type值下可省略items」的校验规则,你需要用JSON Schema的if/then关键字组合,并且确保条件路径和校验范围正确。
正确的JSON Schema示例
{ "$schema": "http://json-schema.org/draft-07/schema#", "type": "object", "properties": { "warehouse_id": { "type": "string" }, "operation_type": { "type": "string" }, "order_id": { "type": "integer" }, "attributes": { "type": "object", "properties": { "volume": { "type": "integer" }, "etd": { "type": "string", "format": "date-time" }, "order_type": { "type": "string" } }, "required": ["order_type"] }, "items": { "type": "array", "items": { "type": "object", "properties": { "sku": { "type": "string" }, "quantity": { "type": "integer" } }, "required": ["sku", "quantity"] } } }, "required": ["warehouse_id", "operation_type", "order_id", "attributes"], "if": { "properties": { "attributes": { "properties": { "order_type": { "const": "ORDER" } }, "required": ["order_type"] } } }, "then": { "required": ["items"] } }
关键逻辑说明
if块精确匹配attributes.order_type等于"ORDER"的场景:通过嵌套properties定位到深层的order_type字段,用const做严格值匹配,同时强制order_type存在(和外层校验呼应,避免空值干扰)。then块指定当if条件满足时,根节点必须包含items字段——这会直接让你提供的那个缺少items的请求被标记为不合法。
常见错误排查
之前的尝试失效大概率是这两个原因:
if条件的路径写错了:比如没有嵌套到attributes对象下,导致无法正确识别order_type的取值。then块的校验范围不对:比如把required: ["items"]写在了attributes的规则里,而不是根节点的规则中。
内容的提问来源于stack exchange,提问作者alejoaguilarG
相关产品推荐
相关产品推荐

