根据JSON模式验证结构

Im trying to write a function that recives a marshaled structure as a []byte and validates against a json schema.

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
", 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.

I already tested the schema agains a json file with data. But can't validate it against a struct.

I'm using github.com/santhosh-tekuri/jsonschema

Let's test a simplified version of your JSONPerson function.

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
", 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.

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.

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