Skip to content

juju/gojsonschema

 
 

Repository files navigation

Build Status

gojsonschema

Description

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

References :

Installation

go get github.com/juju/gojsonschema

Dependencies :

Usage

Example

package main

import (
    "fmt"
    "github.com/juju/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 := gojsonschema.NewReferenceLoader("http://www.some_host.com/schema.json")
  • Local file, using a reference :
loader := gojsonschema.NewReferenceLoader("file:///home/me/schema.json")

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

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

And

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)

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

About

An implementation of JSON Schema, draft v4 - Go language

Resources

Stars

Watchers

Forks

Packages

No packages published

Languages

  • Go 100.0%