0

我有一个像这样的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)。

我已经看到了这个答案,它建议执行以下操作(针对我的用例进行了修改):

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:"

我是否错误地使用了图书馆?如何编写检测此错误的验证脚本?

4

1 回答 1

2

您说架构无效,但您提供的示例并非如此。

未知关键字将被忽略。这是为了允许创建扩展。如果阻止未知关键字,我们将不会拥有各种人和团体创建的扩展生态系统,例如表单生成。

您说 in 的值required是“对不存在的属性的引用”。该required关键字没有指向该properties关键字的链接。

required确定对象必须具有哪些键。

properties确定应如何将子模式应用于对象中的值。

没有必要将 in 的值required也包含在properties. 事实上,在构建复杂的模块化模式时,它们通常不会这样做。

在验证模式是否有效方面,您可以使用 JSON 模式元模式。

鉴于您提供的示例是有效的,就检查您认为不受欢迎的其他事情而言,这取决于您。

一些库可能会提供健全性检查,但这不太可能在您提供的示例中得到体现,因为它们不是错误。

于 2020-01-14T08:56:44.393 回答