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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?