Golang 中的多模式 JSON 验证

Multiple schema JSON validation in Golang

我需要根据 Golang 中的架构验证多个 JSON 文件。

我已经能够通过使用 gojsonschema 来实现它,这确实是一个直接的库。

但是,我现在面临的问题是,我得到的模式依赖于另一个模式,但没有找到加载我需要的所有模式的方法。因此,我的验证总是失败。

这是我的主要架构:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "$ref": "#/definitions/List",
    "definitions": {
        "List": {
            "type": "array",
            "items": {
                "$ref": "#/definitions/Item"
            }
        },
        "Item": {
            "description": "An item ....",
            "type": "object",
            "additionalProperties": false,
            "properties": {
                "property01": {
                    "description": "The property01 code.",
                    "$ref": "./CommonTypes.json#/definitions/Type01Definition"
                }
            },
            "required": [
                "property01"
            ]
        }
    }
}

还有,我还有一个常见的类型:

{
    "$schema": "http://json-schema.org/draft-04/schema#",
    "definitions": {
        "Type01Definition": {
            "description": "The definition for the type 01",
            "type": "string",
            "pattern": "^[A-Z0-9]{3}$"
        }
    }
}

有没有办法使用该库加载多个模式?或者是否有任何其他 Golang 库可以实现这一点?

使用$ref引用文件的方法是使用URL方案指定文件的绝对路径。如果您将 $ref 更改为 "$ref" : "file:///home/user/directory/CommonTypes.json#/definitions/Type01Definition,您的示例将按预期工作。

如果您需要更多的灵活性,您可以尝试 gojsonschemaNewReferenceLoaderFilesystem or switch to a different Golang library https://github.com/santhosh-tekuri/jsonschema。该库允许您添加自定义资源,以便您可以一次加载多个模式。