uses loaders
8 files changed
tree: 5df0d3c6a6c6d7ab0e67d8fa2fdebc0959ebfa11
  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" 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") for _, desc := range result.Errors() { fmt.Printf("- %s\n", desc) } } }

Loading a schema

  • Using HTTP :
    schema, err := gjs.NewSchema("http://www.some_host.com/schema.json")
  • Using a local file :
    schema, err := gjs.NewSchema("file:///home/some_user/schema.json")

Note the URI scheme is used here (file://), also the full path to the file is required.

  • Using a Go map[string]interface{} :
    m := map[string]interface{}{"type": "string"}
    schema, err := gjs.NewSchema(m)
  • Using a JSON string :
    schema, err := gjs.NewSchema(`{"type": "string"}`)

Loading a JSON

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 :

  • string (JSON string)
  • bool (JSON boolean)
  • float64 (JSON number)
  • nil (JSON null)
  • slice (JSON array)
  • map[string]interface{} (JSON object)

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

Validation

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

Uses

gojsonschema uses the following test suite :

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