xeipuuv / gojsonschema

An implementation of JSON Schema, draft v4 v6 & v7 - Go language
2.54k stars 355 forks source link

major api improvement #374

Open amills-vibeirl opened 8 months ago

amills-vibeirl commented 8 months ago

the main workflow looks like this right now:


package main

import (
    "encoding/json"
    "fmt"
    "github.com/xeipuuv/gojsonschema"
    "log"
)

func main() {

    type Person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }

    person := Person{Name: "John Doe", Age: 30}

    personJSON, err := json.Marshal(person)
    if err != nil {
        log.Fatal(err)
    }

    schemaLoader := gojsonschema.NewReferenceLoader("file:///path/to/your/schema.json")
    documentLoader := gojsonschema.NewBytesLoader(personJSON)

    result, err := gojsonschema.Validate(schemaLoader, documentLoader)
    if err != nil {
        log.Fatal(err)
    }

    if result.Valid() {
        fmt.Println("The document is valid")
    } else {
        fmt.Println("The document is not valid. see errors :")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}

but it should look like this instead:


func main() {

    type Person struct {
        Name string `json:"name"`
        Age  int    `json:"age"`
    }

    person := Person{Name: "John Doe", Age: 30}
    schema := gojsonschema.NewReferenceLoader("file:///path/to/your/schema.json")

    result, err := gojsonschema.Validate(schema, person)
    if err != nil {
        log.Fatal(err)
    }

    if result.Valid() {
        fmt.Println("The document is valid")
    } else {
        fmt.Println("The document is not valid. see errors :")
        for _, desc := range result.Errors() {
            fmt.Printf("- %s\n", desc)
        }
    }
}
  1. at the very least the API should convert to JSON for us
  2. you should accept the struct with struct tags, iterate over that instead of comparing json to json-schema

If you are accepting JSON and than Unmarshaling it back to a struct, that's a waste of resources. But I would have to inspect the implementation.

chadgrant commented 7 months ago

bruh, no

amills-vibeirl commented 7 months ago

It's been awhile since I filed this ticket, but looks like I am trying to validate an object before converting to json. Seems reasonable. But if it's more performant to validate after json, etc, then I am fine with that, just seems like an extra step

or the library would convert to json for us, by default. either way.