如何用JSON Schema验证键的字符串值及自定义type类型响应?
JSON Schema验证常见问题解答
Let's tackle your questions one by one, with practical examples to make things clear.
1. 如何使用JSON Schema验证某个键的字符串值?
要验证某个键的字符串值(甚至限定为特定值),你可以结合type关键字和const、enum或pattern来实现,具体取决于你的需求:
- 确保值是字符串类型:直接在属性的Schema中设置
"type": "string"即可。 - 限定为单一固定字符串:用
const强制要求完全匹配某个值。 - 限定为若干个允许的字符串:用
enum定义所有可接受的值列表。 - 匹配正则模式:用
pattern实现灵活的字符串验证(比如邮箱、ID格式)。
示例:验证"status"键的合法值
{ "type": "object", "properties": { "status": { "type": "string", "enum": ["active", "inactive", "pending"] // 仅允许这三个值 } }, "required": ["status"] }
2. 根据type字段的具体取值应用不同验证规则
你的示例是典型的“多态验证”场景——数组中的对象根据type字段的不同,遵循不同的Schema规则。这里的核心方法是使用**oneOf搭配const(适合严格匹配场景)或if/then/else**(适合更灵活的条件逻辑)。
先纠正你示例里的小笔误:数据集里的type: 'admi'和Schema里的"admin"不一致,下面的示例统一为admi以保持一致性。
方案1:oneOf + const(简洁且明确)
这种方式为每个type值单独定义Schema,然后要求数组中的每个项必须严格匹配其中一个Schema:
{ "definitions": { "user_response": { "type": "object", "properties": { "type": { "const": "user" }, // 强制匹配"user" "age": { "type": "number" } }, "required": ["type", "age"], // 两个字段都必填 "additionalProperties": false // 禁止多余的未验证字段 }, "admin_response": { "type": "object", "properties": { "type": { "const": "admi" }, // 强制匹配"admi" "auth": { "type": "object" } }, "required": ["type", "auth"], "additionalProperties": false } }, "type": "object", "properties": { "responses": { "type": "array", "items": { "oneOf": [ { "$ref": "#/definitions/user_response" }, { "$ref": "#/definitions/admin_response" } ] } } }, "required": ["responses"] }
方案2:if/then/else(灵活的条件逻辑)
如果你不想单独定义definitions,if/then/else可以让你直接基于type值编写内联规则:
{ "type": "object", "properties": { "responses": { "type": "array", "items": { "type": "object", "properties": { "type": { "type": "string", "enum": ["user", "admi"] } // 限定允许的type值 }, "required": ["type"], // 当type为"user"时,强制要求age字段 "if": { "properties": { "type": { "const": "user" } } }, "then": { "properties": { "age": { "type": "number" } }, "required": ["age"], "additionalProperties": false }, // 否则,检查type是否为"admi"并强制要求auth字段 "else": { "if": { "properties": { "type": { "const": "admi" } } }, "then": { "properties": { "auth": { "type": "object" } }, "required": ["auth"], "additionalProperties": false } } } } }, "required": ["responses"] }
两种方案都能实现:
type: "user"的对象必须包含数值类型的age字段(且不能有多余字段)type: "admi"的对象必须包含auth对象(且不能有多余字段)- 任何
type值非法的对象都会验证失败
内容的提问来源于stack exchange,提问作者Kivylius
相关产品推荐
相关产品推荐

