如何用JSON Schema实现属性的双向条件必选校验?
JSON Schema 双向约束实现需求
我已经掌握了如何根据某一属性值条件性要求另一属性存在,现在需要实现反向约束。具体场景如下:
- 存在
type属性,包含多个可选值 - 当
type取值为常量"enum"时,必须存在"enum"属性 - 若
"enum"属性存在但type取值不为"enum",则校验失败
以下是我当前使用的Schema:
{ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://example.org/schemas/field", "type": "object", "properties": { "name": { "type": "string" }, "group": { "type": "string" }, "title": { "$ref": "i18n.schema.json" }, "description": { "$ref": "i18n.schema.json" }, "type": { "type": "string", "enum": [ "boolean", "string", "strings", "path", "enum", "map", "integer", "password" ] }, "default": { "$ref": "value.schema.json" }, "required": { "type": "boolean" }, "dependencies": { "type": "array", "items": { "$ref": "dependency.schema.json" } }, "enum": { "type": "string" }, "map": { "$ref": "map.schema.json" } }, "required": [ "name", "title", "type" ], "anyOf": [ { "if": { "properties": { "type": { "const": "enum" } } }, "then": { "required": [ "enum" ] } }, { "if": { "properties": { "type": { "const": "map" } } }, "then": { "required": [ "map" ] } } ], "additionalProperties": false }
补充说明
有效JSON示例
{ "type": "enum", "enum": "foo" }
无效JSON示例
- 存在
enum属性,但type取值不为"enum":
{ "type": "string", "enum": "foo" }
type取值为常量"enum",但enum属性不存在:
{ "type": "enum" }
内容的提问来源于stack exchange,提问作者Mirrana
相关产品推荐
相关产品推荐

