简体   繁体   English

根据JSON模式验证结构

[英]Validate struct against JSON schema

Im trying to write a function that recives a marshaled structure as a []byte and validates against a json schema. 我试图编写一个函数来将一个封送处理的结构作为[] byte接收,并针对json模式进行验证。

type Person struct {
    ID        string   `json:"id,omitempty" xml:"id,attr"`
    Firstname string   `json:"firstname,omitempty" xml:"name>first" `
    Lastname  string   `json:"lastname,omitempty" xml:"name>last"`
    Address   *Address `json:"address,omitempty"`
}

//JSONPerson parses a person struct to a byte array
func JSONPerson(person []Person) []byte {
    var complete []byte
    for _, item := range person {
        output, err := json.Marshal(item)
        if err != nil {
            fmt.Printf("Error: %v\n", err)
        }
        complete = append(complete, output...)
    }
    return complete
}

func ValidateByte(person []byte) {
    //Loads the schema
    schema, err := jsonschema.Compile("Schemas/test.json")
    if err != nil {
        panic(err)
    }
    reader := bytes.NewReader(person)
    if err = schema.Validate(reader); err != nil {
        panic(err)
    } else {
        fmt.Println("Works fine")
    }
}

When executing I get this error http: panic serving [::1]:50664: invalid character { after top-level value. 执行时,我收到以下错误消息:http:紧急服务[:: 1]:50664:无效字符{位于顶级值之后。

I already tested the schema agains a json file with data. 我已经测试了带有数据的json文件。 But can't validate it against a struct. 但是无法针对结构进行验证。

I'm using github.com/santhosh-tekuri/jsonschema 我正在使用github.com/santhosh-tekuri/jsonschema

Let's test a simplified version of your JSONPerson function. 让我们测试一下JSONPerson函数的简化版本。

package main

import (
    "encoding/json"
    "fmt"
)

type Person struct {
    ID   string `json:"id,omitempty"`
    Name string `json:"name,omitempty"`
}

func JSONPerson(person []Person) []byte {
    var complete []byte
    for _, item := range person {
        output, err := json.Marshal(item)
        if err != nil {
            fmt.Printf("Error: %v\n", err)
        }
        complete = append(complete, output...)
    }
    return complete
}

func main() {
    person := []Person{
        Person{"id1", "name1"},
        Person{"id2", "name2"},
    }
    fmt.Println(string(JSONPerson(person)))
}

The output is: 输出为:

{"id":"id1","name":"name1"}{"id":"id2","name":"name2"}

The error you are seeing during schema validation, "invalid character { after top-level value" , refers to the second { which makes this input invalid JSON. 在模式验证期间看到的错误"invalid character { after top-level value"指第二个{ ,它使此输入无效JSON。

JSONPerson is intended to output a JSON array so you will need to make sure the output is wrapped in [ brackets ] and that there are commas in between the array elements. JSONPerson用于输出JSON数组,因此您需要确保输出包装在[方括号]中,并且数组元素之间必须有逗号。

[{"id":"id1","name":"name1"},{"id":"id2","name":"name2"}]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM