为何JSON Schema验证未检测到orderId的类型不符合要求?
为何JSON Schema未检测到数据验证错误?
你的验证不生效是因为Schema的结构存在致命错误,同时还有几个语法细节问题,逐一说明:
核心问题:顶层对象的属性定义未放在properties字段内
JSON Schema中,要验证对象的属性,必须把属性规则放在properties字段下,你直接将retMsg、result作为顶层键,这不符合JSON Schema的规范,导致这些规则完全被忽略。
其他细节错误
- JSON Schema的类型关键字是
"string",不是Python里的"str" - draft-04不支持
const关键字,如果你需要固定值验证,在draft-04中可以用enum: ["OK"]替代;如果想使用const,需要将Schema的draft版本升级到draft-06及以上
修正后的Schema
from jsonschema import validate # 升级到draft-06以支持const关键字,或用enum兼容draft-04 schema = { "$schema": "https://json-schema.org/draft-06/schema#", "type": "object", "properties": { # 必须添加该字段包裹属性规则 "retMsg": { "type": "string", # 修正为JSON Schema标准类型值 "const": "OK" }, "result": { "type": "object", "required": ["orderId", "orderLinkId"], "properties": { "orderId": {"type": "string"}, # 修正为标准类型值 "orderLinkId": {"type": "string"} } } }, "required": ["retMsg", "result"] } raw_data = { "retMsg": "OK", "result": { "orderId": [], "orderLinkId": "abcde" } } validate(instance=raw_data, schema=schema)
验证结果
运行修正后的代码会触发预期的验证错误:
jsonschema.exceptions.ValidationError: [] is not of type 'string' Failed validating 'type' in schema['properties']['result']['properties']['orderId']: {'type': 'string'} On instance['result']['orderId']: []
内容的提问来源于stack exchange,提问作者stas stas
相关产品推荐
相关产品推荐

