jsonschema

package module
v0.0.0-...-2baf11c Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2018 License: MIT Imports: 14 Imported by: 0

README

jsonschema

Qri GoDoc License Codecov CI Go Report Card

golang implementation of the JSON Schema Specification, which lets you write JSON that validates some other json. Rad.

Package Features
  • Encode schemas back to JSON
  • Supply Your own Custom Validators
  • Uses Standard Go idioms
Getting Involved

We would love involvement from more people! If you notice any errors or would like to submit changes, please see our Contributing Guidelines.

Developing

We've set up a separate document for developer guidelines!

Basic Usage

Here's a quick example pulled from the godoc:

package main

import (
	"encoding/json"
	"fmt"

	"github.com/qri-io/jsonschema"
)

func main() {
	var schemaData = []byte(`{
      "title": "Person",
      "type": "object",
      "properties": {
          "firstName": {
              "type": "string"
          },
          "lastName": {
              "type": "string"
          },
          "age": {
              "description": "Age in years",
              "type": "integer",
              "minimum": 0
          },
          "friends": {
            "type" : "array",
            "items" : { "title" : "REFERENCE", "$ref" : "#" }
          }
      },
      "required": ["firstName", "lastName"]
    }`)

	rs := &jsonschema.RootSchema{}
	if err := json.Unmarshal(schemaData, rs); err != nil {
		panic("unmarshal schema: " + err.Error())
	}

	var valid = []byte(`{
    "firstName" : "George",
    "lastName" : "Michael"
    }`)

	if errors := rs.ValidateBytes(valid); len(errors) > 0 {
		panic(err)
	}

	var invalidPerson = []byte(`{
    "firstName" : "Prince"
    }`)
	if errors := rs.ValidateBytes(invalidPerson); len(errors) > 0 {
  	fmt.Println(errs[0].Error())
  }

	var invalidFriend = []byte(`{
    "firstName" : "Jay",
    "lastName" : "Z",
    "friends" : [{
      "firstName" : "Nas"
      }]
    }`)
	if errors := rs.ValidateBytes(invalidFriend); len(errors) > 0 {
  	fmt.Println(errors[0].Error())
  }
}

Custom Validators

The godoc gives an example of how to supply your own validators to extend the standard keywords supported by the spec.

It involves two steps that should happen before allocating any RootSchema instances that use the validator:

  1. create a custom type that implements the Validator interface
  2. call RegisterValidator with the keyword you'd like to detect in JSON, and a ValMaker function.
package main

import (
  "encoding/json"
  "fmt"
  "github.com/qri-io/jsonschema"
)

// your custom validator
type IsFoo bool

// newIsFoo is a jsonschama.ValMaker
func newIsFoo() jsonschema.Validator {
  return new(IsFoo)
}

// Validate implements jsonschema.Validator
func (f IsFoo) Validate(data interface{}) []jsonschema.ValError {
  if str, ok := data.(string); ok {
    if str != "foo" {
      return []jsonschema.ValError{
        {Message: fmt.Sprintf("'%s' is not foo. It should be foo. plz make '%s' == foo. plz", str, str)},
      }
    }
  }
  return nil
}

func main() {
  // register a custom validator by supplying a function
  // that creates new instances of your Validator.
  jsonschema.RegisterValidator("foo", newIsFoo)

  schBytes := []byte(`{ "foo": true }`)

  // parse a schema that uses your custom keyword
  rs := new(jsonschema.RootSchema)
  if err := json.Unmarshal(schBytes, rs); err != nil {
    // Real programs handle errors.
    panic(err)
  }

  // validate some JSON
  errors := rs.ValidateBytes([]byte(`"bar"`))

  // print le error
  fmt.Println(errs[0].Error())

  // Output: 'bar' is not foo. It should be foo. plz make 'bar' == foo. plz
}

Documentation

Overview

Package jsonschema implements draft-handrews-json-schema-validation-00 JSON Schema (application/schema+json) has several purposes, one of which is JSON instance validation. This document specifies a vocabulary for JSON Schema to describe the meaning of JSON documents, provide hints for user interfaces working with JSON data, and to make assertions about what a valid document must look like.

Index

Constants

This section is empty.

Variables

View Source
var DefaultSchemaPool = Definitions{}

DefaultSchemaPool is a package level map of schemas by identifier remote references are cached here.

View Source
var DefaultValidators = map[string]ValMaker{

	"type":  NewType,
	"enum":  NewEnum,
	"const": NewConst,

	"multipleOf":       NewMultipleOf,
	"maximum":          NewMaximum,
	"exclusiveMaximum": NewExclusiveMaximum,
	"minimum":          NewMinimum,
	"exclusiveMinimum": NewExclusiveMinimum,

	"maxLength": NewMaxLength,
	"minLength": NewMinLength,
	"pattern":   NewPattern,

	"allOf": NewAllOf,
	"anyOf": NewAnyOf,
	"oneOf": NewOneOf,
	"not":   NewNot,

	"items":           NewItems,
	"additionalItems": NewAdditionalItems,
	"maxItems":        NewMaxItems,
	"minItems":        NewMinItems,
	"uniqueItems":     NewUniqueItems,
	"contains":        NewContains,

	"maxProperties":        NewMaxProperties,
	"minProperties":        NewMinProperties,
	"required":             NewRequired,
	"properties":           NewProperties,
	"patternProperties":    NewPatternProperties,
	"additionalProperties": NewAdditionalProperties,
	"dependencies":         NewDependencies,
	"propertyNames":        NewPropertyNames,

	"if":   NewIf,
	"then": NewThen,
	"else": NewElse,

	"format": NewFormat,
}

DefaultValidators is a map of JSON keywords to Validators to draw from when decoding schemas

View Source
var MaxValueErrStringLen = 20

MaxValueErrStringLen sets how long a value can be before it's length is truncated when printing error strings a special value of -1 disables output trimming

Functions

func AddError

func AddError(errs *[]ValError, propPath string, data interface{}, msg string)

AddError creates and appends a ValError to errs

func DataType

func DataType(data interface{}) string

DataType gives the primitive json type of a standard json-decoded value, plus the special case "integer" for when numbers are whole

func InvalidValueString

func InvalidValueString(data interface{}) string

InvalidValueString returns the errored value as a string

func RegisterValidator

func RegisterValidator(propName string, maker ValMaker)

RegisterValidator adds a validator to DefaultValidators. Custom Validators should satisfy the validator interface, and be able to get cleanly endcode/decode to JSON

Types

type AdditionalItems

type AdditionalItems struct {
	Schema *Schema
	// contains filtered or unexported fields
}

AdditionalItems determines how child instances validate for arrays, and does not directly validate the immediate instance itself. If "Items" is an array of schemas, validation succeeds if every instance element at a position greater than the size of "Items" validates against "AdditionalItems". Otherwise, "AdditionalItems" MUST be ignored, as the "Items" schema (possibly the default value of an empty schema) is applied to all elements. Omitting this keyword has the same behavior as an empty schema.

func (*AdditionalItems) JSONChildren

func (a *AdditionalItems) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for AdditionalItems

func (*AdditionalItems) JSONProp

func (a *AdditionalItems) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for AdditionalItems

func (*AdditionalItems) UnmarshalJSON

func (a *AdditionalItems) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for AdditionalItems

func (*AdditionalItems) Validate

func (a *AdditionalItems) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for AdditionalItems

type AdditionalProperties

type AdditionalProperties struct {
	Properties *Properties

	Schema *Schema
	// contains filtered or unexported fields
}

AdditionalProperties determines how child instances validate for objects, and does not directly validate the immediate instance itself. Validation with "AdditionalProperties" applies only to the child values of instance names that do not match any names in "Properties", and do not match any regular expression in "PatternProperties". For all such Properties, validation succeeds if the child instance validates against the "AdditionalProperties" schema. Omitting this keyword has the same behavior as an empty schema.

func (*AdditionalProperties) JSONChildren

func (ap *AdditionalProperties) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for AdditionalProperties

func (*AdditionalProperties) JSONProp

func (ap *AdditionalProperties) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for AdditionalProperties

func (AdditionalProperties) MarshalJSON

func (ap AdditionalProperties) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for AdditionalProperties

func (*AdditionalProperties) UnmarshalJSON

func (ap *AdditionalProperties) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for AdditionalProperties

func (AdditionalProperties) Validate

func (ap AdditionalProperties) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for AdditionalProperties

type AllOf

type AllOf []*Schema

AllOf MUST be a non-empty array. Each item of the array MUST be a valid JSON Schema. An instance validates successfully against this keyword if it validates successfully against all schemas defined by this keyword's value.

func (AllOf) JSONChildren

func (a AllOf) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for AllOf

func (AllOf) JSONProp

func (a AllOf) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for AllOf

func (AllOf) Validate

func (a AllOf) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the validator interface for AllOf

type AnyOf

type AnyOf []*Schema

AnyOf MUST be a non-empty array. Each item of the array MUST be a valid JSON Schema. An instance validates successfully against this keyword if it validates successfully against at least one schema defined by this keyword's value.

func (AnyOf) JSONChildren

func (a AnyOf) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for AnyOf

func (AnyOf) JSONProp

func (a AnyOf) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for AnyOf

func (AnyOf) Validate

func (a AnyOf) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the validator interface for AnyOf

type BaseValidator

type BaseValidator struct {
	// contains filtered or unexported fields
}

BaseValidator is a foundation for building a validator

func (BaseValidator) AddError

func (b BaseValidator) AddError(errs *[]ValError, propPath string, data interface{}, msg string)

AddError is a convenience method for appending a new error to an existing error slice

func (BaseValidator) Path

func (b BaseValidator) Path() string

Path gives this validator's path

func (*BaseValidator) SetPath

func (b *BaseValidator) SetPath(path string)

SetPath sets base validator's path

type Const

type Const json.RawMessage

Const MAY be of any type, including null. An instance validates successfully against this keyword if its value is equal to the value of the keyword.

func (Const) JSONProp

func (c Const) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Const

func (Const) MarshalJSON

func (c Const) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Const

func (Const) Path

func (c Const) Path() string

Path gives a jsonpointer path to the validator

func (Const) String

func (c Const) String() string

String implements the Stringer interface for Const

func (*Const) UnmarshalJSON

func (c *Const) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Const

func (Const) Validate

func (c Const) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the validate interface for Const

type Contains

type Contains Schema

Contains validates that an array instance is valid against "Contains" if at least one of its elements is valid against the given schema.

func (Contains) JSONChildren

func (c Contains) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Contains

func (Contains) JSONProp

func (c Contains) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Contains

func (*Contains) UnmarshalJSON

func (c *Contains) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Contains

func (*Contains) Validate

func (c *Contains) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for Contains

type Definitions

type Definitions map[string]*Schema

Definitions implements a map of schemas while also satsfying the JSON traversal methods

func (Definitions) JSONChildren

func (d Definitions) JSONChildren() (r map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Definitions

func (Definitions) JSONProp

func (d Definitions) JSONProp(name string) interface{}

JSONProp implements the JSONPather for Definitions

type Dependencies

type Dependencies map[string]Dependency

Dependencies : [CREF1] This keyword specifies rules that are evaluated if the instance is an object and contains a certain property. This keyword's value MUST be an object. Each property specifies a Dependency. Each Dependency value MUST be an array or a valid JSON Schema. If the Dependency value is a subschema, and the Dependency key is a property in the instance, the entire instance must validate against the Dependency value. If the Dependency value is an array, each element in the array, if any, MUST be a string, and MUST be unique. If the Dependency key is a property in the instance, each of the items in the Dependency value must be a property that exists in the instance. Omitting this keyword has the same behavior as an empty object.

func (Dependencies) JSONProp

func (d Dependencies) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Dependencies

func (Dependencies) Validate

func (d Dependencies) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for Dependencies

type Dependency

type Dependency struct {
	// contains filtered or unexported fields
}

Dependency is an instance used only in the Dependencies proprty

func (Dependency) MarshalJSON

func (d Dependency) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Dependency

func (*Dependency) UnmarshalJSON

func (d *Dependency) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Dependencies

func (Dependency) Validate

func (d Dependency) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for Dependency

type Else

type Else Schema

Else MUST be a valid JSON Schema. When present alongside of "if", the instance successfully validates against this keyword if it fails to validate against the "if"'s subschema, and successfully validates against this keyword's subschema. When "if" is absent, or the instance successfully validates against its subschema, validation against this keyword always succeeds. Implementations SHOULD avoid attempting to validate against the subschema in these cases.

func (Else) JSONChildren

func (e Else) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Else

func (Else) JSONProp

func (e Else) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Else

func (Else) MarshalJSON

func (e Else) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Else

func (*Else) UnmarshalJSON

func (e *Else) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Else

func (*Else) Validate

func (e *Else) Validate(propPath string, data interface{}, err *[]ValError)

Validate implements the Validator interface for Else

type Enum

type Enum []Const

Enum validates successfully against this keyword if its value is equal to one of the elements in this keyword's array value. Elements in the array SHOULD be unique. Elements in the array might be of any value, including null.

func (Enum) JSONChildren

func (e Enum) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Enum

func (Enum) JSONProp

func (e Enum) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Enum

func (Enum) Path

func (e Enum) Path() string

Path gives a jsonpointer path to the validator

func (Enum) String

func (e Enum) String() string

String implements the stringer interface for Enum

func (Enum) Validate

func (e Enum) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for Enum

type ExclusiveMaximum

type ExclusiveMaximum float64

ExclusiveMaximum MUST be number, representing an exclusive upper limit for a numeric instance. If the instance is a number, then the instance is valid only if it has a value strictly less than (not equal to) "Exclusivemaximum".

func (ExclusiveMaximum) Validate

func (m ExclusiveMaximum) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for ExclusiveMaximum

type ExclusiveMinimum

type ExclusiveMinimum float64

ExclusiveMinimum MUST be number, representing an exclusive lower limit for a numeric instance. If the instance is a number, then the instance is valid only if it has a value strictly greater than (not equal to) "ExclusiveMinimum".

func (ExclusiveMinimum) Validate

func (m ExclusiveMinimum) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for ExclusiveMinimum

type Format

type Format string

Format implements semantic validation from section 7 of jsonschema draft 7 The "format" keyword functions as both an annotation (Section 3.3) and as an assertion (Section 3.2). While no special effort is required to implement it as an annotation conveying semantic meaning, implementing validation is non-trivial. Implementations MAY support the "format" keyword as a validation assertion. Should they choose to do so:

they SHOULD implement validation for attributes defined below;
they SHOULD offer an option to disable validation for this keyword.

Implementations MAY add custom format attributes. S ave for agreement between parties, schema authors SHALL NOT expect a peer implementation to support this keyword and/or custom format attributes.

func (Format) Validate

func (f Format) Validate(propPath string, data interface{}, errs *[]ValError)

Validate validates input against a keyword

type If

type If struct {
	Schema Schema
	Then   *Then
	Else   *Else
}

If MUST be a valid JSON Schema. Instances that successfully validate against this keyword's subschema MUST also be valid against the subschema value of the "Then" keyword, if present. Instances that fail to validate against this keyword's subschema MUST also be valid against the subschema value of the "Elsee" keyword. Validation of the instance against this keyword on its own always succeeds, regardless of the validation outcome of against its subschema.

func (If) JSONChildren

func (i If) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for If

func (If) JSONProp

func (i If) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for If

func (If) MarshalJSON

func (i If) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for If

func (*If) UnmarshalJSON

func (i *If) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for If

func (*If) Validate

func (i *If) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for If

type Items

type Items struct {
	Schemas []*Schema
	// contains filtered or unexported fields
}

Items MUST be either a valid JSON Schema or an array of valid JSON Schemas. This keyword determines how child instances validate for arrays, and does not directly validate the immediate instance itself.

  • If "Items" is a schema, validation succeeds if all elements in the array successfully validate against that schema.
  • If "Items" is an array of schemas, validation succeeds if each element of the instance validates against the schema at the same position, if any.
  • Omitting this keyword has the same behavior as an empty schema.

func (Items) JSONChildren

func (it Items) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Items

func (Items) JSONProp

func (it Items) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Items

func (Items) MarshalJSON

func (it Items) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Items

func (*Items) UnmarshalJSON

func (it *Items) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Items

func (Items) Validate

func (it Items) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for Items

type JSONContainer

type JSONContainer interface {
	// JSONChildren should return all immidiate children of this element
	JSONChildren() map[string]JSONPather
}

JSONContainer is an interface that enables tree traversal by listing the immideate children of an object

type JSONPather

type JSONPather interface {
	// JSONProp take a string references for a given JSON property
	// implementations must return any matching property of that name
	// or nil if no such subproperty exists.
	// Note this also applies to array values, which are expected to interpret
	// valid numbers as an array index
	JSONProp(name string) interface{}
}

JSONPather makes validators traversible by JSON-pointers, which is required to support references in JSON schemas.

type MaxItems

type MaxItems int

MaxItems MUST be a non-negative integer. An array instance is valid against "MaxItems" if its size is less than, or equal to, the value of this keyword.

func (MaxItems) Validate

func (m MaxItems) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for MaxItems

type MaxLength

type MaxLength int

MaxLength MUST be a non-negative integer. A string instance is valid against this keyword if its length is less than, or equal to, the value of this keyword. The length of a string instance is defined as the number of its characters as defined by RFC 7159 [RFC7159].

func (MaxLength) Validate

func (m MaxLength) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for MaxLength

type MaxProperties

type MaxProperties int

MaxProperties MUST be a non-negative integer. An object instance is valid against "MaxProperties" if its number of Properties is less than, or equal to, the value of this keyword.

func (MaxProperties) Validate

func (m MaxProperties) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for MaxProperties

type Maximum

type Maximum float64

Maximum MUST be a number, representing an inclusive upper limit for a numeric instance. If the instance is a number, then this keyword validates only if the instance is less than or exactly equal to "Maximum".

func (Maximum) Validate

func (m Maximum) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for Maximum

type MinItems

type MinItems int

MinItems MUST be a non-negative integer. An array instance is valid against "MinItems" if its size is greater than, or equal to, the value of this keyword. Omitting this keyword has the same behavior as a value of 0.

func (MinItems) Validate

func (m MinItems) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for MinItems

type MinLength

type MinLength int

MinLength MUST be a non-negative integer. A string instance is valid against this keyword if its length is greater than, or equal to, the value of this keyword. The length of a string instance is defined as the number of its characters as defined by RFC 7159 [RFC7159]. Omitting this keyword has the same behavior as a value of 0.

func (MinLength) Validate

func (m MinLength) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for MinLength

type Minimum

type Minimum float64

Minimum MUST be a number, representing an inclusive lower limit for a numeric instance. If the instance is a number, then this keyword validates only if the instance is greater than or exactly equal to "Minimum".

func (Minimum) Validate

func (m Minimum) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for Minimum

type MultipleOf

type MultipleOf float64

MultipleOf MUST be a number, strictly greater than 0. MultipleOf validates that a numeric instance is valid only if division by this keyword's value results in an integer.

func (MultipleOf) Validate

func (m MultipleOf) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for MultipleOf

type Not

type Not Schema

Not MUST be a valid JSON Schema. An instance is valid against this keyword if it fails to validate successfully against the schema defined by this keyword.

func (Not) JSONChildren

func (n Not) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Not

func (Not) JSONProp

func (n Not) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Not

func (Not) MarshalJSON

func (n Not) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaller for Not

func (*Not) UnmarshalJSON

func (n *Not) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Not

func (*Not) Validate

func (n *Not) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the validator interface for Not

type OneOf

type OneOf []*Schema

OneOf MUST be a non-empty array. Each item of the array MUST be a valid JSON Schema. An instance validates successfully against this keyword if it validates successfully against exactly one schema defined by this keyword's value.

func (OneOf) JSONChildren

func (o OneOf) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for OneOf

func (OneOf) JSONProp

func (o OneOf) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for OneOf

func (OneOf) Validate

func (o OneOf) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the validator interface for OneOf

type Pattern

type Pattern regexp.Regexp

Pattern MUST be a string. This string SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect. A string instance is considered valid if the regular expression matches the instance successfully. Recall: regular expressions are not implicitly anchored.

func (Pattern) MarshalJSON

func (p Pattern) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for Pattern

func (*Pattern) UnmarshalJSON

func (p *Pattern) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Pattern

func (Pattern) Validate

func (p Pattern) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for Pattern

type PatternProperties

type PatternProperties []patternSchema

PatternProperties determines how child instances validate for objects, and does not directly validate the immediate instance itself. Validation of the primitive instance type against this keyword always succeeds. Validation succeeds if, for each instance name that matches any regular expressions that appear as a property name in this keyword's value, the child instance for that name successfully validates against each schema that corresponds to a matching regular expression. Each property name of this object SHOULD be a valid regular expression, according to the ECMA 262 regular expression dialect. Each property value of this object MUST be a valid JSON Schema. Omitting this keyword has the same behavior as an empty object.

func (PatternProperties) JSONChildren

func (p PatternProperties) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for PatternProperties

func (PatternProperties) JSONProp

func (p PatternProperties) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for PatternProperties

func (PatternProperties) MarshalJSON

func (p PatternProperties) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for PatternProperties

func (*PatternProperties) UnmarshalJSON

func (p *PatternProperties) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for PatternProperties

func (PatternProperties) Validate

func (p PatternProperties) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for PatternProperties

type Properties

type Properties map[string]*Schema

Properties MUST be an object. Each value of this object MUST be a valid JSON Schema. This keyword determines how child instances validate for objects, and does not directly validate the immediate instance itself. Validation succeeds if, for each name that appears in both the instance and as a name within this keyword's value, the child instance for that name successfully validates against the corresponding schema. Omitting this keyword has the same behavior as an empty object.

func (Properties) JSONChildren

func (p Properties) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Properties

func (Properties) JSONProp

func (p Properties) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Properties

func (Properties) Validate

func (p Properties) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for Properties

type PropertyNames

type PropertyNames Schema

PropertyNames checks if every property name in the instance validates against the provided schema if the instance is an object. Note the property name that the schema is testing will always be a string. Omitting this keyword has the same behavior as an empty schema.

func (PropertyNames) JSONChildren

func (p PropertyNames) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for PropertyNames

func (PropertyNames) JSONProp

func (p PropertyNames) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Properties

func (PropertyNames) MarshalJSON

func (p PropertyNames) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler for PropertyNames

func (*PropertyNames) UnmarshalJSON

func (p *PropertyNames) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for PropertyNames

func (PropertyNames) Validate

func (p PropertyNames) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for PropertyNames

type Required

type Required []string

Required ensures that for a given object instance, every item in the array is the name of a property in the instance. The value of this keyword MUST be an array. Elements of this array, if any, MUST be strings, and MUST be unique. Omitting this keyword has the same behavior as an empty array.

func (Required) JSONProp

func (r Required) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Required

func (Required) Validate

func (r Required) Validate(propPath string, dataRaw interface{}, errs *[]ValError)

Validate implements the validator interface for Required

type RootSchema

type RootSchema struct {
	Schema
	// The "$schema" keyword is both used as a JSON Schema version
	// identifier and the location of a resource which is itself a JSON
	// Schema, which describes any schema written for this particular
	// version. The value of this keyword MUST be a URI [RFC3986]
	// (containing a scheme) and this URI MUST be normalized. The
	// current schema MUST be valid against the meta-schema identified
	// by this URI. If this URI identifies a retrievable resource, that
	// resource SHOULD be of media type "application/schema+json". The
	// "$schema" keyword SHOULD be used in a root schema. Values for
	// this property are defined in other documents and by other
	// parties. JSON Schema implementations SHOULD implement support
	// for current and previous published drafts of JSON Schema
	// vocabularies as deemed reasonable.
	SchemaURI string `json:"$schema"`
}

RootSchema is a top-level Schema.

func Must

func Must(jsonString string) *RootSchema

Must turns a JSON string into a *RootSchema, panicing if parsing fails. Useful for declaring Schemas in Go code.

func (*RootSchema) FetchRemoteReferences

func (rs *RootSchema) FetchRemoteReferences() error

FetchRemoteReferences grabs any url-based schema references that cannot be locally resolved via network requests

func (*RootSchema) TopLevelType

func (rs *RootSchema) TopLevelType() string

TopLevelType returns a string representing the schema's top-level type.

func (*RootSchema) UnmarshalJSON

func (rs *RootSchema) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for RootSchema

func (*RootSchema) ValidateBytes

func (rs *RootSchema) ValidateBytes(data []byte) ([]ValError, error)

ValidateBytes performs schema validation against a slice of json byte data

type Schema

type Schema struct {

	// The "$id" keyword defines a URI for the schema, and the base URI
	// that other URI references within the schema are resolved
	// against. A subschema's "$id" is resolved against the base URI of
	// its parent schema. If no parent sets an explicit base with
	// "$id", the base URI is that of the entire document, as
	// determined per RFC 3986 section 5 [RFC3986].
	ID string `json:"$id,omitempty"`
	// Title and description can be used to decorate a user interface
	// with information about the data produced by this user interface.
	// A title will preferably be short.
	Title string `json:"title,omitempty"`
	// Description provides an explanation about the purpose
	// of the instance described by this schema.
	Description string `json:"description,omitempty"`
	// There are no restrictions placed on the value of this keyword.
	// When multiple occurrences of this keyword are applicable to a
	// single sub-instance, implementations SHOULD remove duplicates.
	// This keyword can be used to supply a default JSON value
	// associated with a particular schema. It is RECOMMENDED that a
	// default value be valid against the associated schema.
	Default interface{} `json:"default,omitempty"`
	// The value of this keyword MUST be an array. There are no
	// restrictions placed on the values within the array. When
	// multiple occurrences of this keyword are applicable to a single
	// sub-instance, implementations MUST provide a flat array of all
	// values rather than an array of arrays. This keyword can be used
	// to provide sample JSON values associated with a particular
	// schema, for the purpose of illustrating usage. It is
	// RECOMMENDED that these values be valid against the associated
	// schema. Implementations MAY use the value(s) of "default", if
	// present, as an additional example. If "examples" is absent,
	// "default" MAY still be used in this manner.
	Examples []interface{} `json:"examples,omitempty"`
	// If "readOnly" has a value of boolean true, it indicates that the
	// value of the instance is managed exclusively by the owning
	// authority, and attempts by an application to modify the value of
	// this property are expected to be ignored or rejected by that
	// owning authority. An instance document that is marked as
	// "readOnly for the entire document MAY be ignored if sent to the
	// owning authority, or MAY result in an error, at the authority's
	// discretion. For example, "readOnly" would be used to mark a
	// database-generated serial number as read-only, while "writeOnly"
	// would be used to mark a password input field. These keywords can
	// be used to assist in user interface instance generation. In
	// particular, an application MAY choose to use a widget that hides
	// input values as they are typed for write-only fields. Omitting
	// these keywords has the same behavior as values of false.
	ReadOnly *bool `json:"readOnly,omitempty"`
	// If "writeOnly" has a value of boolean true, it indicates that
	// the value is never present when the instance is retrieved from
	// the owning authority. It can be present when sent to the owning
	// authority to update or create the document (or the resource it
	// represents), but it will not be included in any updated or newly
	// created version of the instance. An instance document that is
	// marked as "writeOnly" for the entire document MAY be returned as
	// a blank document of some sort, or MAY produce an error upon
	// retrieval, or have the retrieval request ignored, at the
	// authority's discretion.
	WriteOnly *bool `json:"writeOnly,omitempty"`
	// This keyword is reserved for comments from schema authors to
	// readers or maintainers of the schema. The value of this keyword
	// MUST be a string. Implementations MUST NOT present this string
	// to end users. Tools for editing schemas SHOULD support
	// displaying and editing this keyword. The value of this keyword
	// MAY be used in debug or error output which is intended for
	// developers making use of schemas. Schema vocabularies SHOULD
	// allow "$comment" within any object containing vocabulary
	// keywords. Implementations MAY assume "$comment" is allowed
	// unless the vocabulary specifically forbids it. Vocabularies MUST
	// NOT specify any effect of "$comment" beyond what is described in
	// this specification.
	Comment string `json:"comment,omitempty"`
	// Ref is used to reference a schema, and provides the ability to
	// validate recursive structures through self-reference. An object
	// schema with a "$ref" property MUST be interpreted as a "$ref"
	// reference. The value of the "$ref" property MUST be a URI
	// Reference. Resolved against the current URI base, it identifies
	// the URI of a schema to use. All other properties in a "$ref"
	// object MUST be ignored. The URI is not a network locator, only
	// an identifier. A schema need not be downloadable from the
	// address if it is a network-addressable URL, and implementations
	// SHOULD NOT assume they should perform a network operation when
	// they encounter a network-addressable URI. A schema MUST NOT be
	// run into an infinite loop against a schema. For example, if two
	// schemas "#alice" and "#bob" both have an "allOf" property that
	// refers to the other, a naive validator might get stuck in an
	// infinite recursive loop trying to validate the instance. Schemas
	// SHOULD NOT make use of infinite recursive nesting like this; the
	// behavior is undefined.
	Ref string `json:"$ref,omitempty"`
	// Format functions as both an annotation (Section 3.3) and as an
	// assertion (Section 3.2).
	// While no special effort is required to implement it as an
	// annotation conveying semantic meaning,
	// implementing validation is non-trivial.
	Format string `json:"format,omitempty"`

	// Definitions provides a standardized location for schema authors
	// to inline re-usable JSON Schemas into a more general schema. The
	// keyword does not directly affect the validation result.
	Definitions Definitions `json:"definitions,omitempty"`

	Validators map[string]Validator
	// contains filtered or unexported fields
}

Schema is the root JSON-schema struct A JSON Schema vocabulary is a set of keywords defined for a particular purpose. The vocabulary specifies the meaning of its keywords as assertions, annotations, and/or any vocabulary-defined keyword category.

The two companion standards to this document each define a vocabulary: One for instance validation, and one for hypermedia annotations.

Vocabularies are the primary mechanism for extensibility within the JSON Schema media type. Vocabularies may be defined by any entity. Vocabulary authors SHOULD take care to avoid keyword name collisions if the vocabulary is intended for broad use, and potentially combined with other vocabularies. JSON Schema does not provide any formal namespacing system, but also does not constrain keyword names, allowing for any number of namespacing approaches.

Vocabularies may build on each other, such as by defining the behavior of their keywords with respect to the behavior of keywords from another vocabulary, or by using a keyword from another vocabulary with a restricted or expanded set of acceptable values. Not all such vocabulary re-use will result in a new vocabulary that is compatible with the vocabulary on which it is built.

Vocabulary authors SHOULD clearly document what level of compatibility, if any, is expected. A schema that itself describes a schema is called a meta-schema. Meta-schemas are used to validate JSON Schemas and specify which vocabulary it is using. [CREF1] A JSON Schema MUST be an object or a boolean.

func (Schema) JSONChildren

func (s Schema) JSONChildren() (ch map[string]JSONPather)

JSONChildren implements the JSONContainer interface for Schema

func (Schema) JSONProp

func (s Schema) JSONProp(name string) interface{}

JSONProp implements the JSONPather for Schema

func (Schema) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface for Schema

func (*Schema) Path

func (s *Schema) Path() string

Path gives a jsonpointer path to the validator

func (*Schema) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface for Schema

func (*Schema) Validate

func (s *Schema) Validate(propPath string, data interface{}, errs *[]ValError)

Validate uses the schema to check an instance, collecting validation errors in a slice

type Then

type Then Schema

Then MUST be a valid JSON Schema. When present alongside of "if", the instance successfully validates against this keyword if it validates against both the "if"'s subschema and this keyword's subschema. When "if" is absent, or the instance fails to validate against its subschema, validation against this keyword always succeeds. Implementations SHOULD avoid attempting to validate against the subschema in these cases.

func (Then) JSONChildren

func (t Then) JSONChildren() (res map[string]JSONPather)

JSONChildren implements the JSONContainer interface for If

func (Then) JSONProp

func (t Then) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Then

func (Then) MarshalJSON

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

MarshalJSON implements json.Marshaler for Then

func (*Then) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface for Then

func (*Then) Validate

func (t *Then) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for Then

type Type

type Type struct {
	BaseValidator
	// contains filtered or unexported fields
}

Type specifies one of the six json primitive types. The value of this keyword MUST be either a string or an array. If it is an array, elements of the array MUST be strings and MUST be unique. String values MUST be one of the six primitive types ("null", "boolean", "object", "array", "number", or "string"), or "integer" which matches any number with a zero fractional part. An instance validates if and only if the instance is in any of the sets listed for this keyword.

func (Type) JSONProp

func (t Type) JSONProp(name string) interface{}

JSONProp implements JSON property name indexing for Type

func (Type) MarshalJSON

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

MarshalJSON implements the json.Marshaler interface for Type

func (Type) String

func (t Type) String() string

String returns the type(s) as a string, or unknown if there is no known type.

func (*Type) UnmarshalJSON

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

UnmarshalJSON implements the json.Unmarshaler interface for Type

func (Type) Validate

func (t Type) Validate(propPath string, data interface{}, errs *[]ValError)

Validate checks to see if input data satisfies the type constraint

type UniqueItems

type UniqueItems bool

UniqueItems requires array instance elements be unique If this keyword has boolean value false, the instance validates successfully. If it has boolean value true, the instance validates successfully if all of its elements are unique. Omitting this keyword has the same behavior as a value of false.

func (*UniqueItems) Validate

func (u *UniqueItems) Validate(propPath string, data interface{}, errs *[]ValError)

Validate implements the Validator interface for UniqueItems

type ValError

type ValError struct {
	// PropertyPath is a string path that leads to the
	// property that produced the error
	PropertyPath string `json:"propertyPath,omitempty"`
	// InvalidValue is the value that returned the error
	InvalidValue interface{} `json:"invalidValue,omitempty"`
	// RulePath is the path to the rule that errored
	RulePath string `json:"rulePath,omitempty"`
	// Message is a human-readable description of the error
	Message string `json:"message"`
}

ValError represents a single error in an instance of a schema The only absolutely-required property is Message.

func (ValError) Error

func (v ValError) Error() string

Error implements the error interface for ValError

type ValMaker

type ValMaker func() Validator

ValMaker is a function that generates instances of a validator. Calls to ValMaker will be passed directly to json.Marshal, so the returned value should be a pointer

type Validator

type Validator interface {
	// Validate checks decoded JSON data and writes
	// validation errors (if any) to an outparam slice of ValErrors
	// propPath indicates the position of data in the json tree
	Validate(propPath string, data interface{}, errs *[]ValError)
}

Validator is an interface for anything that can validate. JSON-Schema keywords are all examples of validators

func NewAdditionalItems

func NewAdditionalItems() Validator

NewAdditionalItems creates a new AdditionalItems validator

func NewAdditionalProperties

func NewAdditionalProperties() Validator

NewAdditionalProperties allocates a new AdditionalProperties validator

func NewAllOf

func NewAllOf() Validator

NewAllOf creates a new AllOf validator

func NewAnyOf

func NewAnyOf() Validator

NewAnyOf creates a new AnyOf validator

func NewConst

func NewConst() Validator

NewConst creates a new Const Validator

func NewContains

func NewContains() Validator

NewContains creates a new Contains validator

func NewDependencies

func NewDependencies() Validator

NewDependencies allocates a new Dependencies validator

func NewElse

func NewElse() Validator

NewElse allocates a new Else validator

func NewEnum

func NewEnum() Validator

NewEnum creates a new Enum Validator

func NewExclusiveMaximum

func NewExclusiveMaximum() Validator

NewExclusiveMaximum allocates a new ExclusiveMaximum validator

func NewExclusiveMinimum

func NewExclusiveMinimum() Validator

NewExclusiveMinimum allocates a new ExclusiveMinimum validator

func NewFormat

func NewFormat() Validator

NewFormat allocates a new Format validator

func NewIf

func NewIf() Validator

NewIf allocates a new If validator

func NewItems

func NewItems() Validator

NewItems creates a new Items validator

func NewMaxItems

func NewMaxItems() Validator

NewMaxItems creates a new MaxItems validator

func NewMaxLength

func NewMaxLength() Validator

NewMaxLength allocates a new MaxLength validator

func NewMaxProperties

func NewMaxProperties() Validator

NewMaxProperties allocates a new MaxProperties validator

func NewMaximum

func NewMaximum() Validator

NewMaximum allocates a new Maximum validator

func NewMinItems

func NewMinItems() Validator

NewMinItems creates a new MinItems validator

func NewMinLength

func NewMinLength() Validator

NewMinLength allocates a new MinLength validator

func NewMinProperties

func NewMinProperties() Validator

NewMinProperties allocates a new MinProperties validator

func NewMinimum

func NewMinimum() Validator

NewMinimum allocates a new Minimum validator

func NewMultipleOf

func NewMultipleOf() Validator

NewMultipleOf allocates a new MultipleOf validator

func NewNot

func NewNot() Validator

NewNot creates a new Not validator

func NewOneOf

func NewOneOf() Validator

NewOneOf creates a new OneOf validator

func NewPattern

func NewPattern() Validator

NewPattern allocates a new Pattern validator

func NewPatternProperties

func NewPatternProperties() Validator

NewPatternProperties allocates a new PatternProperties validator

func NewProperties

func NewProperties() Validator

NewProperties allocates a new Properties validator

func NewPropertyNames

func NewPropertyNames() Validator

NewPropertyNames allocates a new PropertyNames validator

func NewRequired

func NewRequired() Validator

NewRequired allocates a new Required validator

func NewThen

func NewThen() Validator

NewThen allocates a new Then validator

func NewType

func NewType() Validator

NewType creates a new Type Validator

func NewUniqueItems

func NewUniqueItems() Validator

NewUniqueItems creates a new UniqueItems validator

Jump to

Keyboard shortcuts

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