Merge branch 'master' of https://github.com/xeipuuv/gojsonschema
tree: 4aad6e3500b4dfc5aa47f8ed997d69fda7b63589
  1. json_schema_test_suite/
  2. .travis.yml
  3. internalLog.go
  4. jsonContext.go
  5. jsonLoader.go
  6. LICENSE-APACHE-2.0.txt
  7. locales.go
  8. README.md
  9. result.go
  10. schema.go
  11. schema_test.go
  12. schemaPool.go
  13. schemaReferencePool.go
  14. schemaType.go
  15. subSchema.go
  16. types.go
  17. utils.go
  18. utils_test.go
  19. validation.go
README.md

Build Status

gojsonschema

Description

An implementation of JSON Schema, based on IETF's draft v4 - Go language

References :

Installation

go get github.com/xeipuuv/gojsonschema

Dependencies :

Usage

Example


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) } } }

Loaders

There are various ways to load your JSON data. In order to load your schemas and documents, first declare an appropriate loader :

  • Web / HTTP, using a reference :
loader, err := gojsonschema.NewReferenceLoader("http://www.some_host.com/schema.json")
  • Local file, using a reference :
loader, err := gojsonschema.NewReferenceLoader("file:///home/me/schema.json")

References use the URI scheme, the prefix (file://) and a full path to the file are required.

  • Custom Go types :
m := map[string]interface{}{"type": "string"}
loader, err := gojsonschema.NewGoLoader(m)
  • JSON strings :
loader, err := gojsonschema.NewStringLoader(`{"type": "string"}`)

Validation

Once the loaders are set, validation is easy :

result, err := gojsonschema.Validate(schemaLoader, documentLoader)

Alternatively, you might want to load a schema only once and process to multiple validations :

schema, err := gojsonschema.NewSchema(schemaLoader)
...
result1, err := schema.Validate(documentLoader1)
...
result2, err := schema.Validate(documentLoader2)
...
// etc ...

To check the result :

    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)
        }
    }

Uses

gojsonschema uses the following test suite :

https://github.com/json-schema/JSON-Schema-Test-Suite