【发布时间】:2020-04-30 11:04:04
【问题描述】:
我有一个像这样的JSON Schema 文件,其中包含几个故意的错误:
{
"$schema": "http://json-schema.org/schema#",
"type": "object",
"description": "MWE for JSON Schema Validation",
"properties": {
"valid_prop": {
"type": ["string", "number"],
"description": "This can be either a string or a number."
},
"invalid_prop": {
// NOTE: "type:" here should have been "type" (without the colon)
"type:": ["string", "null"],
"description": "Note the extra colon in the name of the type property above"
}
},
// NOTE: Reference to a non-existent property
"required": ["valid_prop", "nonexistent_prop"]
}
我想编写一个 Python 脚本(或者,更好的是,安装一个带有 PiP 的 CLI)来查找这些错误。
我见过this answer,它建议执行以下操作(针对我的用例进行了修改):
import json
from jsonschema import Draft4Validator
with open('./my-schema.json') as schemaf:
schema = json.loads('\n'.join(schemaf.readlines()))
Draft4Validator.check_schema(my_schema)
print("OK!") # on invalid schema we don't get here
但上面的脚本没有检测到架构文件中的任何一个错误。我会怀疑它至少检测到"type:" 属性中的额外冒号。
我是否错误地使用了库?如何编写检测此错误的验证脚本?
【问题讨论】:
-
不是应该可以在JSONschema中描述JSONschema吗?我想知道他们是否在规范中的某个地方这样做了。在四处寻找时找不到它,但如果它存在的话,我不会感到惊讶......
-
仅供参考,
schema = json.load(schemaf)是一种更简洁的文件加载方式。即使schema = json.loads(schemaf.read())也比逐行阅读要再次加入他们要好。.readlines()还会在每一行中保留换行符,因此与\n连接会产生双倍行距的结果。 -
来自json-schema.org/understanding-json-schema/about.html#about"但是,由于JSON Schema不能包含任意代码,因此无法表达数据元素之间的关系存在一定的限制。任何“验证工具” ” 因此,对于足够复杂的数据格式,可能会有两个验证阶段:一个在模式(或结构)级别,一个在语义级别。后一种检查可能需要使用更通用的方法来实现编程语言。” - 所以,是的,不是的。尽管可以捕获像
"type:"这样的错误。
标签: python json jsonschema python-jsonschema