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 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了