An implementation of JSON Schema, based on IETF's draft v4 - Go language
References:
go get github.com/xeipuuv/gojsonschema
package main import ( "fmt" gjs "github.com/xeipuuv/gojsonschema" ) func main() { schema, err := gjs.NewSchema("file:///home/me/schema.json") if err != nil { panic(err.Error()) } document, err := gjs.GetFile("/home/me/document.json") if err != nil { panic(err.Error()) } result, err := schema.Validate(document) 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") // display validation errors for _, desc := range result.Errors() { fmt.Printf("- %s\n", desc) } } }
Schemas can be loaded remotely from a HTTP URL :
schema, err := gjs.NewSchema("http://myhost/schema.json")
From a local file, using the file URI scheme:
schema, err := gjs.NewSchema("file:///home/me/schema.json")
You may also load the schema from within your code, using a map[string]interface{} variable or a JSON string.
Note that schemas loaded from non-HTTP are subject to limitations, they need to be standalone schemas; That means references to local files and/or remote files within these schemas will not work.
m := map[string]interface{}{
"type": "string"}
schema, err := gjs.NewSchema(m)
Or
schema, err := gjs.NewSchema(`{"type": "string"}`)
The library virtually accepts any form of JSON since it uses reflection to validate against the schema.
You may use and combine go types like :
You can declare your JSON from within your code, using a map / interface{} :
document := map[string]interface{}{
"name": "john"}
Or a JSON string:
document := `{"name": "john"}`
Helper functions are also available to load from a HTTP URL :
document, err := gjs.GetHTTP("http://host/data.json")
Or a local file :
document, err := gjs.GetFile("/home/me/data.json")
Once the schema and the JSON to validate are loaded, validation phase becomes easy :
result, err := schema.Validate(document)
Check the result with:
if result.Valid() { // Your Json is valid }
If not valid, you can loop through the error messages returned by the validation phase :
for _, desc := range result.Errors() {
fmt.Printf("Error: %s\n", desc)
}
https://github.com/xeipuuv/gojsonpointer
https://github.com/xeipuuv/gojsonreference
https://github.com/stretchr/testify/assert
gojsonschema uses the following test suite :