schema

package module
Version: v0.0.0-...-e38a2f2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jun 4, 2018 License: MIT Imports: 14 Imported by: 0

README

go-jsschema

Build Status

GoDoc

JSON Schema for Go

SYNOPSIS

package schema_test

import (
  "log"

  "github.com/lestrrat/go-jsschema"
  "github.com/lestrrat/go-jsschema/validator"
)

func Example() {
  s, err := schema.ReadFile("schema.json")
  if err != nil {
    log.Printf("failed to read schema: %s", err)
    return
  }

  for name, pdef := range s.Properties {
    // Do what you will with `pdef`, which contain
    // Schema information for `name` property
    _ = name
    _ = pdef
  }

  // You can also validate an arbitrary piece of data
  var p interface{} // initialize using json.Unmarshal...
  v := validator.New(s)
  if err := v.Validate(p); err != nil {
    log.Printf("failed to validate data: %s", err)
  }
}

DESCRIPTION

This packages parses a JSON Schema file, and allows you to inspect, modify the schema, but does nothing more.

If you want to validate using the JSON Schema that you read using this package, look at go-jsval, which allows you to generate validators, so that you don't have to dynamically read in the JSON schema for each instance of your program.

In the same lines, this package does not really care about loading external schemas from various locations (it's just easier to just gather all the schemas in your local system). It is possible to do this via go-jsref if you really want to do it.

BENCHMARKS

Latest version of libraries as of Sep 3 2016.

Benchmarks with gojsonschema are prefixed with Gojsonschema.

Benchmarks without prefixes are about ths package.

$ go test -tags benchmark -benchmem -bench=.
BenchmarkGojsonschemaParse-4            5000        357330 ns/op      167451 B/op       1866 allocs/op
BenchmarkParse-4                     1000000          1577 ns/op        1952 B/op          9 allocs/op
BenchmarkParseAndMakeValidator-4      500000          2806 ns/op        2304 B/op         13 allocs/op
PASS

TODO

  • Properly resolve ids and $refs (it works in simple cases, but elaborate scopes probably don't work)

Contributors

  • Daisuke Maki
  • Nate Finch

References

Name Notes
go-jsval Validator generator
go-jshschema JSON Hyper Schema implementation
go-jsref JSON Reference implementation
go-jspointer JSON Pointer implementations

Documentation

Overview

Example
s, err := schema.ReadFile("schema.json")
if err != nil {
	log.Printf("failed to read schema: %s", err)
	return
}

for name, pdef := range s.Properties {
	// Do what you will with `pdef`, which contain
	// Schema information for `name` property
	_ = name
	_ = pdef
}

// Create a validator
v := validator.New(s)

// You can also validate an arbitrary piece of data
var p interface{} // initialize using json.Unmarshal...
if err := v.Validate(p); err != nil {
	log.Printf("failed to validate data: %s", err)
}
Output:

Index

Examples

Constants

View Source
const (
	// SchemaURL contains the JSON Schema URL
	SchemaURL = `http://json-schema.org/draft-04/schema`
	// HyperSchemaURL contains the JSON Hyper Schema URL
	HyperSchemaURL = `http://json-schema.org/draft-03/hyper-schema`
	// MIMEType contains the MIME used for a JSON Schema
	MIMEType = "application/schema+json"
)

Variables

View Source
var ErrExpectedArrayOfString = errors.New("invalid value: expected array of string")

ErrExpectedArrayOfString is returned when we encounter something other than array of strings

View Source
var ErrInvalidStringArray = ErrExpectedArrayOfString

ErrInvalidStringArray is the same as ErrExpectedArrayOfString. This is here only for backwards compatibility

Functions

This section is empty.

Types

type AdditionalItems

type AdditionalItems struct {
	*Schema
}

AdditionalItems represents schema for additonalItems

type AdditionalProperties

type AdditionalProperties struct {
	*Schema
}

AdditionalProperties represents schema for additonalProperties

type Bool

type Bool struct {
	Val         bool
	Default     bool
	Initialized bool
}

Bool represents a "boolean" value in a JSON Schema, such as "exclusiveMinimum", "exclusiveMaximum", etc.

func (Bool) Bool

func (b Bool) Bool() bool

Bool returns the underlying boolean value for the primitive boolean type

type DependencyMap

type DependencyMap struct {
	Names   map[string][]string
	Schemas map[string]*Schema
}

DependencyMap contains the dependencies defined within this schema. for a given dependency name, you can have either a schema or a list of property names

type Format

type Format string

Format represents one of the pre-defined JSON Schema formats

const (
	FormatDateTime Format = "date-time"
	FormatEmail    Format = "email"
	FormatHostname Format = "hostname"
	FormatIPv4     Format = "ipv4"
	FormatIPv6     Format = "ipv6"
	FormatURI      Format = "uri"
)

The list of pre-defined JSON Schema formats

type Integer

type Integer struct {
	Val         int
	Initialized bool
}

Integer represents a "integer" value in a JSON Schema, such as "minLength", "maxLength", etc.

type ItemSpec

type ItemSpec struct {
	TupleMode bool // If this is true, the positions mean something. if false, len(Schemas) should be 1, and we should apply the same schema validation to all elements
	Schemas   SchemaList
}

ItemSpec represents a specification for `item` field

type Number

type Number struct {
	Val         float64
	Initialized bool
}

Number represents a "number" value in a JSON Schema, such as "minimum", "maximum", etc.

type PrimitiveType

type PrimitiveType int

PrimitiveType represents a JSON Schema primitive type such as "string", "integer", etc.

const (
	UnspecifiedType PrimitiveType = iota
	NullType
	IntegerType
	StringType
	ObjectType
	ArrayType
	BooleanType
	NumberType
)

The list of primitive types

func (PrimitiveType) MarshalJSON

func (t PrimitiveType) MarshalJSON() ([]byte, error)

MarshalJSON seriealises the primitive type into a JSON string

func (PrimitiveType) String

func (t PrimitiveType) String() string

String returns the string representation of this primitive type

func (*PrimitiveType) UnmarshalJSON

func (t *PrimitiveType) UnmarshalJSON(data []byte) error

UnmarshalJSON initializes the primitive type from a JSON string.

type PrimitiveTypes

type PrimitiveTypes []PrimitiveType

PrimitiveTypes is a list of PrimitiveType

func (PrimitiveTypes) Contains

func (pt PrimitiveTypes) Contains(p PrimitiveType) bool

Contains returns true if the list of primitive types contains `p`

func (PrimitiveTypes) Len

func (pt PrimitiveTypes) Len() int

Len returns the length of the list of primitive types

func (PrimitiveTypes) Less

func (pt PrimitiveTypes) Less(i, j int) bool

Less returns true if the i-th element in the list is listed before the j-th element.

func (PrimitiveTypes) Swap

func (pt PrimitiveTypes) Swap(i, j int)

Swap swaps the elements in positions i and j

func (*PrimitiveTypes) UnmarshalJSON

func (pt *PrimitiveTypes) UnmarshalJSON(data []byte) error

UnmarshalJSON initializes the list of primitive types

type Schema

type Schema struct {
	ID          string             `json:"id,omitempty"`
	Title       string             `json:"title,omitempty"`
	Description string             `json:"description,omitempty"`
	Default     interface{}        `json:"default,omitempty"`
	Type        PrimitiveTypes     `json:"type,omitempty"`
	SchemaRef   string             `json:"$schema,omitempty"`
	Definitions map[string]*Schema `json:"definitions,omitempty"`
	Reference   string             `json:"$ref,omitempty"`
	Format      Format             `json:"format,omitempty"`
	Nullable    Bool               `json:"nullable,omitempty"`

	// NumericValidations
	MultipleOf       Number `json:"multipleOf,omitempty"`
	Minimum          Number `json:"minimum,omitempty"`
	Maximum          Number `json:"maximum,omitempty"`
	ExclusiveMinimum Bool   `json:"exclusiveMinimum,omitempty"`
	ExclusiveMaximum Bool   `json:"exclusiveMaximum,omitempty"`

	// StringValidation
	MaxLength Integer        `json:"maxLength,omitempty"`
	MinLength Integer        `json:"minLength,omitempty"`
	Pattern   *regexp.Regexp `json:"pattern,omitempty"`

	// ArrayValidations
	AdditionalItems *AdditionalItems
	Items           *ItemSpec
	MinItems        Integer
	MaxItems        Integer
	UniqueItems     Bool

	// ObjectValidations
	MaxProperties        Integer                    `json:"maxProperties,omitempty"`
	MinProperties        Integer                    `json:"minProperties,omitempty"`
	Required             []string                   `json:"required,omitempty"`
	Dependencies         DependencyMap              `json:"dependencies,omitempty"`
	Properties           map[string]*Schema         `json:"properties,omitempty"`
	AdditionalProperties *AdditionalProperties      `json:"additionalProperties,omitempty"`
	PatternProperties    map[*regexp.Regexp]*Schema `json:"patternProperties,omitempty"`

	Enum   []interface{}          `json:"enum,omitempty"`
	AllOf  SchemaList             `json:"allOf,omitempty"`
	AnyOf  SchemaList             `json:"anyOf,omitempty"`
	OneOf  SchemaList             `json:"oneOf,omitempty"`
	Not    *Schema                `json:"not,omitempty"`
	Extras map[string]interface{} `json:"-"`
	// contains filtered or unexported fields
}

Schema represents a JSON Schema object

func New

func New() *Schema

New creates a new schema object

func Read

func Read(in io.Reader) (*Schema, error)

Read reads from `in` and parses its content to create a new Schema object

func ReadFile

func ReadFile(f string) (*Schema, error)

ReadFile reads the file `f` and parses its content to create a new Schema object

func (*Schema) BaseURL

func (s *Schema) BaseURL() *url.URL

BaseURL returns the base URL registered for this schema

func (*Schema) Decode

func (s *Schema) Decode(in io.Reader) error

Decode reads from `in` and parses its content to initialize the schema object

func (*Schema) Extract

func (s *Schema) Extract(m map[string]interface{}) error

Extract takes a `map[string]interface{}` and initializes the schema

func (*Schema) IsPropRequired

func (s *Schema) IsPropRequired(pname string) bool

IsPropRequired can be used to query this schema if a given property name is required.

func (*Schema) IsResolved

func (s *Schema) IsResolved() bool

IsResolved returns true if this schema has no Reference.

func (*Schema) MarshalJSON

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON serializes the schema into a JSON string

func (*Schema) Resolve

func (s *Schema) Resolve(ctx interface{}) (ref *Schema, err error)

Resolve returns the schema after it has been resolved. If s.Reference is the empty string, the current schema is returned.

`ctx` is an optional context to resolve the reference with. If not specified, the root schema as returned by `Root` will be used.

func (*Schema) ResolveURL

func (s *Schema) ResolveURL(v string) (u *url.URL, err error)

ResolveURL takes a url string, and resolves it if it's a relative URL

func (*Schema) Root

func (s *Schema) Root() *Schema

Root returns the upmost parent schema object within the hierarchy of schemas. For example, the `item` element in a schema for an array is also a schema, and you could reference elements in parent schemas.

func (*Schema) Scope

func (s *Schema) Scope() string

Scope returns the scope ID for this schema

func (*Schema) UnmarshalJSON

func (s *Schema) UnmarshalJSON(data []byte) error

UnmarshalJSON takes a JSON string and initializes the schema

type SchemaList

type SchemaList []*Schema

SchemaList is a list of Schemas

func (*SchemaList) Extract

func (l *SchemaList) Extract(v interface{}) error

Extract takes either a list of `map[string]interface{}` or a single `map[string]interface{}` to initialize this list of schemas

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL