在Golang中进行多个模式的JSON验证

3
我需要使用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库可以实现这一点?


1
第二个问题不适合在SO上讨论:询问我们推荐或寻找书籍、工具、软件库、教程或其他站外资源的问题,因为它们往往会吸引主观的答案和垃圾邮件,所以这些问题不适合在Stack Overflow上讨论。 - Adrian
1个回答

3
使用$ref引用文件的方法是使用URL方案指定文件的绝对路径。如果将$ref更改为类似于"$ref" : "file:///home/user/directory/CommonTypes.json#/definitions/Type01Definition,则您的示例将按预期工作。
如果您需要更多灵活性,可以尝试gojsonschemaNewReferenceLoaderFilesystem或切换到不同的Golanghttps://github.com/santhosh-tekuri/jsonschema。该库允许您添加自定义资源,因此您可以一次加载多个模式。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接