dongmeiwei0226 2018-02-07 16:16
浏览 65
已采纳

Golang中的多模式JSON验证

I need to validate several JSON files against a schema in Golang.

I have been able to achieve it by using gojsonschema, that is really a straight forward library.

However, the problem I'm facing right now is that I have been given with schemas that have dependencies to another schemas and haven't found the way to load all the schemas that I need. Therefore, my validations always fail.

This is my main schema:

{
    "$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"
            ]
        }
    }
}

And, I have another one with common types:

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

Is there a way to load several schemas using that library? Or is there any other Golang library that allows to achieve that?

  • 写回答

1条回答 默认 最新

  • dongsuyou6938 2018-02-07 18:52
    关注

    The way to refer to a file using $ref is to specify the absolute path of the file using a URL scheme. If you change the $ref to look like "$ref" : "file:///home/user/directory/CommonTypes.json#/definitions/Type01Definition, your example will work as expected.

    If you need a bit more flexibility you can either try gojsonschema's NewReferenceLoaderFilesystem or switch to a different Golang library https://github.com/santhosh-tekuri/jsonschema. That library allows you to add custom resources so you can load several schemas at once.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器