Golang中如何通过Gojsonschema路径获取JSON schema

Golang中如何通过Gojsonschema路径获取JSON schema 我正在项目中加载JSON模式,用于根据模式验证传入的JSON数据。

为此,我使用了以下包:https://github.com/xeipuuv/gojsonschema

例如,我尝试这样设置模式文件的路径:

schemaLoader := gojsonschema.NewReferenceLoader("file://./filename.json")

因为JSON文件与Go文件存储在同一个文件夹中。

执行命令:

resultValidate, err := gojsonschema.Validate(schemaLoader, loader)

其中loader是通过请求体结构实例创建的NewGoLoader,返回错误:

err = Reference ./filename.json must be canonical

我哪里做错了? 谢谢!


更多关于Golang中如何通过Gojsonschema路径获取JSON schema的实战教程也可以访问 https://www.itying.com/category-94-b0.html

4 回复

尝试使用绝对路径而不是相对路径,但这只是猜测。

更多关于Golang中如何通过Gojsonschema路径获取JSON schema的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html


当我设置绝对路径时,验证结果返回错误

repo/projectname/vendor/golang.org/x/sys/unix.ENOENT

也许使用其他JSON验证器会更有效?但应该选择哪一个呢?

func (r *JsonReference) IsCanonical() bool {
return (r.HasFileScheme && r.HasFullFilePath) || (!r.HasFileScheme && r.HasFullUrl)
}

架构加载器 := gojsonschema.NewReferenceLoader(“file://./filename.json”)

你需要这个json文件的绝对路径,类似"file://home/blah/blah/filename.json"这样的格式

您遇到的错误是因为 gojsonschema 要求使用规范的 URI 格式来引用本地文件。当使用 file:// 协议时,路径必须是绝对路径而不是相对路径。

以下是正确的实现方式:

package main

import (
    "path/filepath"
    "runtime"

    "github.com/xeipuuv/gojsonschema"
)

func main() {
    // 获取当前文件的绝对路径
    _, filename, _, _ := runtime.Caller(0)
    dir := filepath.Dir(filename)
    
    // 构建JSON schema文件的绝对路径
    schemaPath := filepath.Join(dir, "filename.json")
    
    // 使用file://协议加载schema(必须是绝对路径)
    schemaLoader := gojsonschema.NewReferenceLoader("file://" + schemaPath)
    
    // 您的数据加载器
    loader := gojsonschema.NewGoLoader(yourDataStruct)
    
    // 验证
    result, err := gojsonschema.Validate(schemaLoader, loader)
    if err != nil {
        panic(err.Error())
    }
    
    if result.Valid() {
        println("文档有效")
    } else {
        println("文档无效,错误:")
        for _, desc := range result.Errors() {
            println("- %s", desc)
        }
    }
}

或者,如果您知道文件的绝对路径,可以直接使用:

schemaLoader := gojsonschema.NewReferenceLoader("file:///home/user/project/filename.json")

在Windows系统上,路径格式稍有不同:

// Windows系统
schemaLoader := gojsonschema.NewReferenceLoader("file:///C:/project/filename.json")

另一种替代方法是使用 NewStringLoaderNewBytesLoader 直接加载文件内容:

import (
    "io/ioutil"
    "log"
)

// 直接读取文件内容
schemaBytes, err := ioutil.ReadFile("filename.json")
if err != nil {
    log.Fatal(err)
}

schemaLoader := gojsonschema.NewBytesLoader(schemaBytes)

使用绝对路径的 file:// 引用可以解决 “must be canonical” 错误。

回到顶部