### Install gojsonschema package Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Command to install the gojsonschema library using the go get command. This is the standard method for obtaining Go packages. ```bash go get github.com/xeipuuv/gojsonschema ``` -------------------------------- ### Check validation result in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Example of how to determine if a JSON document is valid after a validation attempt using gojsonschema. It also shows how to access and display any validation errors found. ```go if result.Valid() { fmt.Printf("The document is valid\n") } else { fmt.Printf("The document is not valid. see errors :\n") for _, err := range result.Errors() { // Err implements the ResultError interface fmt.Printf("- %s\n", err) } } ``` -------------------------------- ### Validate JSON document against schema in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Example demonstrating how to validate a JSON document against a JSON schema using the gojsonschema library. It shows how to load the schema and document from files and process the validation result. ```go package main import ( "fmt" "github.com/xeipuuv/gojsonschema" ) func main() { schemaLoader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json") documentLoader := gojsonschema.NewReferenceLoader("file:///home/me/document.json") result, err := gojsonschema.Validate(schemaLoader, documentLoader) if err != nil { panic(err.Error()) } if result.Valid() { fmt.Printf("The document is valid\n") } else { fmt.Printf("The document is not valid. see errors :\n") for _, desc := range result.Errors() { fmt.Printf("- %s\n", desc) } } } ``` -------------------------------- ### Remove Built-in Format Checker in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Shows how to remove a default format checker provided by gojsonschema. This is useful for overriding existing formats or ensuring they are not used. The example demonstrates removing the 'hostname' format checker. ```go import ( "github.com/xeipuuv/gojsonschema" ) gojsonschema.FormatCheckers.Remove("hostname") ``` -------------------------------- ### Add Custom Error to Validation Result in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Provides an example of adding custom validation errors to a gojsonschema result. This is achieved by defining a custom error type that embeds gojsonschema.ResultErrorFields and implementing a constructor function. This allows for more detailed and business-specific error reporting. ```go import ( "github.com/xeipuuv/gojsonschema" ) type AnswerInvalidError struct { gojsonschema.ResultErrorFields } func newAnswerInvalidError(context *gojsonschema.JsonContext, value interface{}, details gojsonschema.ErrorDetails) *AnswerInvalidError { err := AnswerInvalidError{} err.SetContext(context) err.SetType("custom_invalid_error") // it is important to use SetDescriptionFormat() as this is used to call SetDescription() after it has been parsed // using the description of err will be overridden by this. err.SetDescriptionFormat("Answer to the Ultimate Question of Life, the Universe, and Everything is {{.answer}}") err.SetValue(value) err.SetDetails(details) return &err } func main() { // ... assuming schemaLoader, documentLoader are defined s// schema, err := gojsonschema.NewSchema(schemaLoader) // result, err := gojsonschema.Validate(schemaLoader, documentLoader) if true { // some validation condition jsonContext := gojsonschema.NewJsonContext("question", nil) errDetail := gojsonschema.ErrorDetails{ "answer": 42, } // result.AddError( // newAnswerInvalidError( // gojsonschema.NewJsonContext("answer", jsonContext), // 52, // errDetail, // ), // errDetail, // ) } // return result, err return nil, nil // Placeholder } ``` -------------------------------- ### Load JSON Schema/Document from various sources in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Demonstrates different methods for creating loaders for JSON schemas and documents within the gojsonschema library. Supports web references, local files, raw JSON strings, and Go data structures. ```go loader := gojsonschema.NewReferenceLoader("http://www.some_host.com/schema.json") ``` ```go loader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json") ``` ```go loader := gojsonschema.NewStringLoader(`{"type": "string"}`) ``` ```go m := map[string]interface{}{"type": "string"} loader := gojsonschema.NewGoLoader(m) ``` ```go type Root struct { Users []User `json:"users"` } type User struct { Name string `json:"name"` } data := Root{} data.Users = append(data.Users, User{"John"}) data.Users = append(data.Users, User{"Sophia"}) data.Users = append(data.Users, User{"Bill"}) loader := gojsonschema.NewGoLoader(data) ``` -------------------------------- ### Load Local Schemas with gojsonschema Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Demonstrates loading local JSON schemas using gojsonschema's SchemaLoader. Schemas can be added via strings or by referencing existing schemas using `$id`. The main schema is then compiled and used for validation. ```go sl := gojsonsonschema.NewSchemaLoader() loader1 := gojsonsonschema.NewStringLoader(`{ "type" : "string" }`) err := sl.AddSchema("http://some_host.com/string.json", loader1) ``` ```go loader2 := gojsonsonschema.NewStringLoader(`{ "$id" : "http://some_host.com/maxlength.json", "maxLength" : 5 }`) err = sl.AddSchemas(loader2) ``` ```go loader3 := gojsonsonschema.NewStringLoader(`{ "$id" : "http://some_host.com/main.json", "allOf" : [ { "$ref" : "http://some_host.com/string.json" }, { "$ref" : "http://some_host.com/maxlength.json" } ] }`) schema, err := sl.Compile(loader3) documentLoader := gojsonsonschema.NewStringLoader(`"hello world"`) result, err := schema.Validate(documentLoader) ``` ```go err = sl.AddSchemas(loader3) schema, err := sl.Compile(gojsonsonschema.NewReferenceLoader("http://some_host.com/main.json")) ``` -------------------------------- ### Pre-compile schema for multiple validations in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Shows how to compile a JSON schema once and reuse it for validating multiple JSON documents. This approach is more efficient when validating many documents against the same schema. ```go schema, err := gojsonschema.NewSchema(schemaLoader) ... result1, err := schema.Validate(documentLoader1) ... result2, err := schema.Validate(documentLoader2) ... ``` -------------------------------- ### Enable Meta-Schema Validation in gojsonschema Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Shows how to enable meta-schema validation in gojsonschema to catch errors during schema compilation rather than just validation. This is useful for developing and debugging schemas, providing more detailed error messages. ```go sl := gojsonsonschema.NewSchemaLoader() sl.Validate = true err := sl.AddSchemas(gojsonsonschema.NewStringLoader(`{ "$id" : "http://some_host.com/invalid.json", "$schema": "http://json-schema.org/draft-07/schema#", "multipleOf" : true }`)) ``` -------------------------------- ### Add Custom Format Checker in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Demonstrates how to define a custom format checker in Go for the gojsonschema library. This involves creating a struct that implements the FormatChecker interface and registering it with the FormatCheckers library. This allows validation against custom formats defined in JSON schemas. ```go import ( "strings" "github.com/xeipuuv/gojsonschema" ) // Define the format checker type RoleFormatChecker struct {} // Ensure it meets the gojsonschema.FormatChecker interface func (f RoleFormatChecker) IsFormat(input interface{}) bool { asString, ok := input.(string) if ok == false { return false } return strings.HasPrefix("ROLE_", asString) } // Add it to the library gojsonschema.FormatCheckers.Add("role", RoleFormatChecker{}) ``` -------------------------------- ### Add Custom Integer Format Checker in Go Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Illustrates creating a custom format checker in Go for integer types in gojsonschema. This checker verifies if a given number corresponds to a valid user ID by performing a database lookup. It highlights how to handle numeric inputs, which are typically received as float64. ```go import ( "github.com/xeipuuv/gojsonschema" ) // Define the format checker type ValidUserIdFormatChecker struct {} // Ensure it meets the gojsonschema.FormatChecker interface func (f ValidUserIdFormatChecker) IsFormat(input interface{}) bool { asFloat64, ok := input.(float64) // Numbers are always float64 here if ok == false { return false } // XXX // do the magic on the database looking for the int(asFloat64) return true } // Add it to the library gojsonschema.FormatCheckers.Add("ValidUserId", ValidUserIdFormatChecker{}) ``` -------------------------------- ### Define Custom Error Template Functions Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Enables the use of custom functions within error message templates for more complex message formatting. This is achieved by defining a map of function names to interface{} and assigning it to gojsonschema.ErrorTemplateFuncs. ```go gojsonschema.ErrorTemplateFuncs = map[string]interface{}{ "allcaps": func(s string) string { return strings.ToUpper(s) }, } ``` -------------------------------- ### Specify Draft Version with gojsonschema Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Illustrates how to control the JSON schema draft version used by gojsonschema. Auto-detection can be turned off, and specific drafts like Draft7 can be explicitly set. This affects how schemas are parsed and validated. ```go sl := gojsonsonschema.NewSchemaLoader() sl.Draft = gojsonsonschema.Draft7 sl.AutoDetect = false ``` -------------------------------- ### Customize GoJSonSchema Locale Source: https://github.com/xeipuuv/gojsonschema/blob/master/README.md Allows for the customization of error messages by providing a custom locale. This involves creating a new struct that implements the gojsonschema.Locale interface and assigning it to the gojsonschema.Locale variable. ```go gojsonschema.Locale = YourCustomLocale{} ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.