需要了解json模式验证的contains和items关键字的区别

问题描述 投票:0回答:1

我正在使用 python 的 jsonschema 验证库来执行架构验证,下面是与架构版本和示例 json 数据一起使用的代码片段。我的问题是,当我使用 schema 版本一(其中使用 contains 关键字)时,我从代码片段中获得的错误响应非常通用,就像它不会为您提供元素明智的验证失败原因,但当我使用稍作修改时我使用 items 而不是 contains 的模式版本,相同的代码片段在 elemenet 级别给出了详细错误。

有人可以解释一下,为什么会发生这种情况,或者只有在使用

contains 关键字时才会出现这种情况,或者我在代码片段中遗漏了一些内容。

json 架构版本一:

{ "$schema": "http://json-schema.org/draft/2019-09/schema#", "type": "array", "contains": { "type": "number" }, "minContains": 2, "maxContains": 5 }

json 架构版本二:

{ "$schema": "http://json-schema.org/draft/2019-09/schema#", "type": "array", "items": { "type": "number" }, "minContains": 2, "maxContains": 5 }

json数据:

["", "1234"]

代码片段:

import json import jsonschema from jsonschema import Draft201909Validator from jsonschema.exceptions import ValidationError json_file = 'json_schema_validation/sample.json' json_schema_file = 'json_schema_validation/sample_schemav2.json' with open(json_file) as f: rec = json.load(f) with open(json_schema_file) as f: schema = json.load(f) v = Draft201909Validator(schema) errors = sorted(v.iter_errors(rec), key=lambda e: e.path) for error in errors: print("---------------------------------------") print("json_path list:", list(error.path)) print("error_message:", error.message)

使用模式版本二时的输出:

--------------------------------------- json_path list: [0] error_message: '' is not of type 'number' --------------------------------------- json_path list: [1] error_message: '1234' is not of type 'number'

使用模式版本一时的输出:

--------------------------------------- json_path list: [] error_message: ['', '1234'] does not contain items matching the given schema

python json jsonschema json-schema-validator python-jsonschema
1个回答
0
投票
根据 Json Schema 文档,

包含表示数组中至少有一项是有效的

Items表示数组的所有元素都有效

https://json-schema.org/understanding-json-schema/reference/array

因此,由您的用例决定是否要验证至少一项或全部

© www.soinside.com 2019 - 2024. All rights reserved.