JSON Schema patternProperties 与 if/then 处理动态键:替代手动验证循环
patternProperties 通过键名正则表达式约束值类型,if/then 基于判别器添加条件要求,unevaluatedProperties 在组合时关闭模式。这三者共同取代了枚举所有可能键名的手写 Python 验证循环。
本文内容
简明答案
使用 patternProperties 强制匹配命名约定的键携带正确的值类型,使用 if/then 根据判别器值要求额外字段,并使用 unevaluatedProperties:false 拒绝任何未被声明规则覆盖的键。这三个关键字共同取代了枚举每个可能键名的手写 Python 验证循环。
为什么动态键的手动验证很脆弱且模式级规则更可取
当 JSON 对象包含运行时生成的键(如带前缀的标识符或用户定义的标签)时,手写的 Python 验证循环必须枚举每个可能的键名或依赖临时的字符串检查。Python json 模块保证序列化后所有键都是字符串,但它没有机制来限制哪些字符串键是合法的或它们必须持有什么样的值类型。JSON Schema 的 patternProperties 关键字将这一责任转移到声明式合同中,由验证器在应用程序代码运行之前强制执行。
json 文档明确指出:JSON 键值对中的键始终是 str 类型。当字典转换为 JSON 时,字典的所有键都转换为字符串。这意味着模式层是唯一可以在不使用自定义代码的情况下表达键名约束的地方。
import json
from jsonschema import Draft202012Validator
# The json module decodes keys as str but performs zero schema validation.
raw = '{"S_tag": "hello", "I_count": 7, "source": "web"}'
payload = json.loads(raw)
print(type(list(payload.keys())[0])) # <class 'str'>实用建议
除非你有意进行子字符串匹配,否则始终使用 ^ 和 $ 锚定你的 patternProperties 正则表达式。像 "S_" 这样的非锚定模式会同时匹配 "myS_tag" 和 "S_extra",这在用于前缀约定时很少是你想要的结果。
patternProperties:通过键名模式约束值类型
patternProperties 接受从正则表达式到模式的映射。任何匹配正则表达式的实例键都必须满足关联的模式。官方文档演示了 ^S_ 要求字符串和 ^I_ 要求整数。关键细节是,除非使用 ^ 和 $ 锚定,否则正则表达式会在键名的任何位置匹配,因此像 "p" 这样的非锚定模式会意外匹配 "apple"。这是名称遵循命名约定的动态键的主要工具。
不匹配任何模式的键会被 patternProperties 忽略;它们会落入 additionalProperties 或默认被接受。
schema = {
"type": "object",
"patternProperties": {
"^S_": {"type": "string"},
"^I_": {"type": "integer"}
}
}
ok = {"S_25": "This is a string", "I_0": 42}
bad = {"S_0": 42} # starts with S_ but value is not a string
print(list(Draft202012Validator(schema).iter_errors(ok))) # []
print(list(Draft202012Validator(schema).iter_errors(bad))) # 1 ValidationError结合 patternProperties 和 properties 处理已知和未知键
一个模式可以同时通过 properties 声明固定键,并通过 patternProperties 声明动态键。文档提供了一个具体示例:通过 properties 将 builtin 键约束为数字,而 ^S_ 和 ^I_ 前缀通过 patternProperties 约束。不匹配任何模式的键会落入 additionalProperties。这种分层方法取代了常见的反模式,即在一个分支中检查已知键而在另一个分支中检查未知键的单个验证函数。
评估顺序是:properties 处理精确匹配的键,patternProperties 处理正则匹配的键,additionalProperties 处理其他所有内容。每个关键字独立作用于其键的子集。
schema = {
"type": "object",
"properties": {"builtin": {"type": "number"}},
"patternProperties": {
"^S_": {"type": "string"},
"^I_": {"type": "integer"}
},
"additionalProperties": {"type": "string"}
}
# "keyword" matches no pattern, so additionalProperties applies
print(list(Draft202012Validator(schema).iter_errors({"keyword": "value"}))) # []
print(list(Draft202012Validator(schema).iter_errors({"keyword": 42}))) # 1 erroradditionalProperties 作为未匹配键的兜底
additionalProperties 验证未被 properties 或 patternProperties 匹配的键。将其设置为 false 会拒绝声明集合之外的任何键。将其设置为模式会约束所有剩余键的值类型而不枚举它们。文档显示,当 additionalProperties 为 {"type":"string"} 时,值为 42 的键 keyword 会失败。这个关键字是防止任意垃圾进入对象的安全网。
一个常见错误是假设 additionalProperties 能看到通过 allOf 到达的同级子模式中声明的属性。它不能。它只识别其自身子模式中的属性,这就是 unevaluatedProperties 存在的原因。
schema = {
"type": "object",
"properties": {"name": {"type": "string"}},
"additionalProperties": False
}
print(list(Draft202012Validator(schema).iter_errors({"name": "ok"})))
print(list(Draft202012Validator(schema).iter_errors({"name": "ok", "age": 30})))if/then 用于由判别器值驱动的条件字段要求
if/then/else 构造处理某些键的存在或类型取决于另一个键值的场景。文档的地址示例使用 if 检查 type 是否等于 business,然后要求 department 属性。这取代了读取判别器、分支并有条件地验证的手动 Python 代码。
关键见解是 then 仅在 if 匹配时添加约束,从而启用按变体验证而无需为每个变体设置单独的模式。if 子模式必须包含 required 以确保判别器键实际存在;否则,缺失的键会轻易满足 properties 检查并意外触发 then。
schema = {
"type": "object",
"properties": {"type": {"enum": ["residential", "business"]}},
"required": ["type"],
"if": {
"properties": {"type": {"const": "business"}},
"required": ["type"]
},
"then": {
"properties": {"department": {"type": "string"}},
"required": ["department"]
}
}
biz = {"type": "business", "department": "HR"}
res = {"type": "residential"}
print(list(Draft202012Validator(schema).iter_errors(biz))) # []
print(list(Draft202012Validator(schema).iter_errors(res))) # []
print(list(Draft202012Validator(schema).iter_errors({"type": "business"}))) # 1 errorunevaluatedProperties 在 if/then 和 allOf 交互时关闭模式
众所周知的陷阱是 additionalProperties 只能看到其自身子模式中声明的属性,因此通过 allOf 扩展封闭模式会导致错误的拒绝。文档演示了在外部模式中添加的 type 属性会被内部的 additionalProperties:false 拒绝。修复方法是使用 unevaluatedProperties:false,它识别由所有组合子模式评估的属性,包括由 then 引入的属性。
此关键字需要 JSON Schema draft 2019-09 或更高版本。在 Python jsonschema 库中,使用 Draft201909Validator 或 Draft202012Validator。较旧的草稿必须依赖 additionalProperties 并在每个子模式中手动枚举属性,这违背了组合的目的。
schema = {
"type": "object",
"properties": {"source": {"enum": ["web", "queue"]}},
"required": ["source"],
"if": {
"properties": {"source": {"const": "web"}},
"required": ["source"]
},
"then": {"properties": {"url": {"type": "string"}}, "required": ["url"]},
"else": {"properties": {"queue_name": {"type": "string"}}, "required": ["queue_name"]},
"patternProperties": {
"^S_": {"type": "string"},
"^I_": {"type": "integer"}
},
"additionalProperties": {"type": "string"},
"unevaluatedProperties": False
}
good = {"source": "web", "url": "https://example.com", "S_tag": "hi", "I_n": 1}
bad = {"source": "web", "url": "x", "S_tag": 42}
print(list(Draft202012Validator(schema).iter_errors(good))) # []
print(list(Draft202012Validator(schema).iter_errors(bad))) # 1 errorminProperties 和 maxProperties 限制动态键的基数
patternProperties 约束动态键的样子但不约束有多少个。minProperties 和 maxProperties 设置对象中键总数的整数界限。文档展示了一个具有 minProperties:2 和 maxProperties:3 的模式,它拒绝空对象、单键对象和四键对象,同时接受两键和三键对象。
这防止了带前缀键的无界增长,这可能表明存在错误或注入尝试。结合 patternProperties,你可以以声明方式获得形状和基数保证。
schema = {"type": "object", "minProperties": 2, "maxProperties": 3}
print(list(Draft202012Validator(schema).iter_errors({}))) # 1 error
print(list(Draft202012Validator(schema).iter_errors({"a": 0}))) # 1 error
print(list(Draft202012Validator(schema).iter_errors({"a": 0, "b": 1}))) # []
print(list(Draft202012Validator(schema).iter_errors({"a":0,"b":1,"c":2,"d":3}))) # 1 error适用性限制以及何时回退到程序化检查
patternProperties 无法表达键间关系,例如:如果键 X 存在,则键 Y 也必须存在且具有匹配的值。除了 if/then 使用固定判别器涵盖的内容外,任意的跨键逻辑需要程序化的后验证步骤。
patternProperties 中的正则表达式匹配区分大小写,并且在大多数验证器实现中不支持 Unicode 属性转义。Python json 模块本身不执行模式验证,因此始终需要单独的库,如 jsonschema(支持 unevaluatedProperties 的版本 4.0 或更高)。对于不遵循命名约定的高度不规则键集,手动验证函数比笨重的模式更简单。
jsonschema 库不是标准库的一部分。安装它请使用:pip install jsonschema。对于包括 unevaluatedProperties 支持的 draft 2020-12,确保 jsonschema 4.0+ 并可选地安装 jsonschema[format] 以进行格式验证。
import json
from jsonschema import Draft202012Validator
# Demonstrating a case where patternProperties alone is insufficient:
# "If S_owner exists, then I_owner_id must also exist" cannot be
# expressed declaratively. A post-validation check is needed.
def cross_key_check(obj):
if "S_owner" in obj and "I_owner_id" not in obj:
return ["S_owner present but I_owner_id missing"]
return []
payload = json.loads('{"S_owner": "alice", "source": "web", "url": "x"}')
print(cross_key_check(payload)) # ['S_owner present but I_owner_id missing']检查清单
- patternProperties 正则表达式必须使用 ^ 和 $ 锚定,以避免在较长的键名上进行意外的子字符串匹配。
- unevaluatedProperties:false 需要 draft 2019-09 或更高版本;较旧的草稿会静默忽略它,使 additionalProperties 成为唯一的关闭机制。
- if 子模式必须包含判别器键的 required;否则,缺失的键会轻易通过 properties 检查并意外触发 then。
- additionalProperties 只识别其自身子模式中的属性,而不是通过 allOf 或 if/then 到达的同级子模式中的属性。
- Python json 模块执行零模式验证;它仅编码和解码,因此始终需要 jsonschema 或等效库。
适用范围
patternProperties 无法表达两个不同动态键之间的关系,如匹配对。patternProperties 中的正则表达式默认不区分大小写,且在大多数验证器实现中不支持 Unicode 属性类。Python json 模块执行零模式验证;它仅编码和解码,因此始终需要单独的验证器。unevaluatedProperties 需要 JSON Schema draft 2019-09 或更高版本;较旧的草稿必须依赖 additionalProperties 并在每个子模式中手动枚举属性。对于不遵循命名约定的高度不规则键集,手动验证函数比笨重的模式更简单。