jsonschema

package
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Jul 18, 2023 License: Apache-2.0 Imports: 18 Imported by: 0

Documentation

Overview

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

This is copied from https://github.com/santhosh-tekuri/jsonschema/

Index

Constants

This section is empty.

Variables

View Source
var (
	Draft4    = &Draft{version: 4, id: "id", boolSchema: false}
	Draft6    = &Draft{version: 6, id: "$id", boolSchema: true}
	Draft7    = &Draft{version: 7, id: "$id", boolSchema: true}
	Draft2019 = &Draft{version: 2019, id: "$id", boolSchema: true}
	Draft2020 = &Draft{version: 2020, id: "$id", boolSchema: true}
)

supported drafts

View Source
var Decoders = map[string]func(string) ([]byte, error){
	"base64": base64.StdEncoding.DecodeString,
}

Decoders is a registry of functions, which know how to decode string encoded in specific format.

New Decoders can be registered by adding to this map. Key is encoding name, value is function that knows how to decode string in that format.

View Source
var Formats = map[string]func(interface{}) bool{
	"date-time":             isDateTime,
	"date":                  isDate,
	"time":                  isTime,
	"duration":              isDuration,
	"period":                isPeriod,
	"hostname":              isHostname,
	"email":                 isEmail,
	"ip-address":            isIPV4,
	"ipv4":                  isIPV4,
	"ipv6":                  isIPV6,
	"uri":                   isURI,
	"iri":                   isURI,
	"uri-reference":         isURIReference,
	"uriref":                isURIReference,
	"iri-reference":         isURIReference,
	"uri-template":          isURITemplate,
	"regex":                 isRegex,
	"json-pointer":          isJSONPointer,
	"relative-json-pointer": isRelativeJSONPointer,
	"uuid":                  isUUID,
}

Formats is a registry of functions, which know how to validate a specific format.

New Formats can be registered by adding to this map. Key is format name, value is function that knows how to validate that format.

View Source
var LoadURL = func(s string) (io.ReadCloser, error) {
	u, err := url.Parse(s)
	if err != nil {
		return nil, err
	}
	loader, ok := Loaders[u.Scheme]
	if !ok {
		return nil, LoaderNotFoundError(s)

	}
	return loader(s)
}

LoadURL loads document at given absolute URL. The default implementation uses Loaders registry to lookup by schema and uses that loader.

Users can change this variable, if they would like to take complete responsibility of loading given URL. Used by Compiler if its LoadURL field is nil.

View Source
var Loaders = map[string]func(url string) (io.ReadCloser, error){
	"file": loadFileURL,
}

Loaders is a registry of functions, which know how to load absolute url of specific schema.

New loaders can be registered by adding to this map. Key is schema, value is function that knows how to load url of that schema

View Source
var MediaTypes = map[string]func([]byte) error{
	"application/json": validateJSON,
}

MediaTypes is a registry of functions, which know how to validate whether the bytes represent data of that mediaType.

New mediaTypes can be registered by adding to this map. Key is mediaType name, value is function that knows how to validate that mediaType.

Functions

This section is empty.

Types

type Compiler

type Compiler struct {
	// Draft represents the draft used when '$schema' attribute is missing.
	//
	// This defaults to latest supported draft (currently 2020-12).
	Draft *Draft

	// ExtractAnnotations tells whether schema annotations has to be extracted
	// in compiled Schema or not.
	ExtractAnnotations bool

	// LoadURL loads the document at given absolute URL.
	//
	// If nil, package global LoadURL is used.
	LoadURL func(s string) (io.ReadCloser, error)

	// AssertFormat for specifications >= draft2019-09.
	AssertFormat bool

	// AssertContent for specifications >= draft2019-09.
	AssertContent bool
	// contains filtered or unexported fields
}

A Compiler represents a json-schema compiler.

func NewCompiler

func NewCompiler() *Compiler

NewCompiler returns a json-schema Compiler object. if '$schema' attribute is missing, it is treated as draft7. to change this behavior change Compiler.Draft value

func (*Compiler) AddResource

func (c *Compiler) AddResource(url string, r io.Reader) error

AddResource adds in-memory resource to the compiler.

Note that url must not have fragment

func (*Compiler) Compile

func (c *Compiler) Compile(url string) (*Schema, error)

Compile parses json-schema at given url returns, if successful, a Schema object that can be used to match against json.

error returned will be of type *SchemaError

func (*Compiler) MustCompile

func (c *Compiler) MustCompile(url string) *Schema

MustCompile is like Compile but panics if the url cannot be compiled to *Schema. It simplifies safe initialization of global variables holding compiled Schemas.

func (*Compiler) RegisterExtension

func (c *Compiler) RegisterExtension(name string, meta *Schema, ext ExtCompiler)

RegisterExtension registers custom keyword(s) into this compiler.

name is extension name, used only to avoid name collisions. meta captures the metaschema for the new keywords. This is used to validate the schema before calling ext.Compile.

type CompilerContext

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

CompilerContext provides additional context required in compiling for extension.

func (CompilerContext) Compile

func (ctx CompilerContext) Compile(schPath string, applicableOnSameInstance bool) (*Schema, error)

Compile compiles given value at ptr into *Schema. This is useful in implementing keyword like allOf/not/patternProperties.

schPath is the relative-json-pointer to the schema to be compiled from parent schema.

applicableOnSameInstance tells whether current schema and the given schema are applied on same instance value. this is used to detect infinite loop in schema.

func (CompilerContext) CompileRef

func (ctx CompilerContext) CompileRef(ref string, refPath string, applicableOnSameInstance bool) (*Schema, error)

CompileRef compiles the schema referenced by ref uri

refPath is the relative-json-pointer to ref.

applicableOnSameInstance tells whether current schema and the given schema are applied on same instance value. this is used to detect infinite loop in schema.

type Draft

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

A Draft represents json-schema draft

type ExtCompiler

type ExtCompiler interface {
	// Compile compiles the custom keywords in schema m and returns its compiled representation.
	// if the schema m does not contain the keywords defined by this extension,
	// compiled representation nil should be returned.
	Compile(ctx CompilerContext, m map[string]interface{}) (ExtSchema, error)
}

ExtCompiler compiles custom keyword(s) into ExtSchema.

type ExtSchema

type ExtSchema interface {
	// Validate validates the json value v with this ExtSchema.
	// Returned error must be *ValidationError.
	Validate(ctx ValidationContext, v interface{}) error
}

ExtSchema is schema representation of custom keyword(s)

type InfiniteLoopError

type InfiniteLoopError string

InfiniteLoopError is returned by Compile/Validate. this gives url#keywordLocation that lead to infinity loop.

func (InfiniteLoopError) Error

func (e InfiniteLoopError) Error() string

type InvalidJSONTypeError

type InvalidJSONTypeError string

InvalidJSONTypeError is the error type returned by ValidateInterface. this tells that specified go object is not valid jsonType.

func (InvalidJSONTypeError) Error

func (e InvalidJSONTypeError) Error() string

type LoaderNotFoundError

type LoaderNotFoundError string

LoaderNotFoundError is the error type returned by Load function. It tells that no Loader is registered for that URL Scheme.

func (LoaderNotFoundError) Error

func (e LoaderNotFoundError) Error() string

type Schema

type Schema struct {
	Location string // absolute location

	// type agnostic validations
	Format string

	Always          *bool // always pass/fail. used when booleans are used as schemas in draft-07.
	Ref             *Schema
	RecursiveAnchor bool
	RecursiveRef    *Schema
	DynamicAnchor   string
	DynamicRef      *Schema
	Types           []string      // allowed types.
	Constant        []interface{} // first element in slice is constant value. note: slice is used to capture nil constant.
	Enum            []interface{} // allowed values.

	Not   *Schema
	AllOf []*Schema
	AnyOf []*Schema
	OneOf []*Schema
	If    *Schema
	Then  *Schema // nil, when If is nil.
	Else  *Schema // nil, when If is nil.

	// object validations
	MinProperties         int      // -1 if not specified.
	MaxProperties         int      // -1 if not specified.
	Required              []string // list of required properties.
	Properties            map[string]*Schema
	PropertyNames         *Schema
	RegexProperties       bool // property names must be valid regex. used only in draft4 as workaround in metaschema.
	PatternProperties     map[*regexp.Regexp]*Schema
	AdditionalProperties  interface{}            // nil or bool or *Schema.
	Dependencies          map[string]interface{} // map value is *Schema or []string.
	DependentRequired     map[string][]string
	DependentSchemas      map[string]*Schema
	UnevaluatedProperties *Schema

	// array validations
	MinItems         int // -1 if not specified.
	MaxItems         int // -1 if not specified.
	UniqueItems      bool
	Items            interface{} // nil or *Schema or []*Schema
	AdditionalItems  interface{} // nil or bool or *Schema.
	PrefixItems      []*Schema
	Items2020        *Schema // items keyword reintroduced in draft 2020-12
	Contains         *Schema
	ContainsEval     bool // whether any item in an array that passes validation of the contains schema is considered "evaluated"
	MinContains      int  // 1 if not specified
	MaxContains      int  // -1 if not specified
	UnevaluatedItems *Schema

	// string validations
	MinLength       int // -1 if not specified.
	MaxLength       int // -1 if not specified.
	Pattern         *regexp.Regexp
	ContentEncoding string

	ContentMediaType string

	// number validators
	Minimum          *big.Rat
	ExclusiveMinimum *big.Rat
	Maximum          *big.Rat
	ExclusiveMaximum *big.Rat
	MultipleOf       *big.Rat

	// annotations. captured only when Compiler.ExtractAnnotations is true.
	Title       string
	Description string
	Default     interface{}
	Comment     string
	ReadOnly    bool
	WriteOnly   bool
	Examples    []interface{}
	Deprecated  bool

	// user defined extensions
	Extensions map[string]ExtSchema
	// contains filtered or unexported fields
}

A Schema represents compiled version of json-schema.

func Compile

func Compile(url string) (*Schema, error)

Compile parses json-schema at given url returns, if successful, a Schema object that can be used to match against json.

Returned error can be *SchemaError

func CompileString

func CompileString(url, schema string) (*Schema, error)

CompileString parses and compiles the given schema with given base url.

func MustCompile

func MustCompile(url string) *Schema

MustCompile is like Compile but panics if the url cannot be compiled to *Schema. It simplifies safe initialization of global variables holding compiled Schemas.

func MustCompileString

func MustCompileString(url, schema string) *Schema

MustCompileString is like CompileString but panics on error. It simplified safe initialization of global variables holding compiled Schema.

func (*Schema) String

func (s *Schema) String() string

func (*Schema) Validate

func (s *Schema) Validate(v interface{}) (err error)

Validate validates given doc, against the json-schema s.

the v must be the raw json value. for number precision unmarshal with json.UseNumber().

returns *ValidationError if v does not confirm with schema s. returns InfiniteLoopError if it detects loop during validation. returns InvalidJSONTypeError if it detects any non json value in v.

type SchemaError

type SchemaError struct {
	// SchemaURL is the url to json-schema that filed to compile.
	// This is helpful, if your schema refers to external schemas
	SchemaURL string

	// Err is the error that occurred during compilation.
	// It could be ValidationError, because compilation validates
	// given schema against the json meta-schema
	Err error
}

SchemaError is the error type returned by Compile.

func (*SchemaError) Error

func (se *SchemaError) Error() string

func (*SchemaError) GoString

func (se *SchemaError) GoString() string

func (*SchemaError) Unwrap

func (se *SchemaError) Unwrap() error

type ValidationContext

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

ValidationContext provides additional context required in validating for extension.

func (ValidationContext) Error

func (ctx ValidationContext) Error(keywordPath string, format string, a ...interface{}) *ValidationError

Error used to construct validation error by extensions.

keywordPath is relative-json-pointer to keyword.

func (ValidationContext) EvaluatedItem

func (ctx ValidationContext) EvaluatedItem(index int)

EvaluatedItem marks given index of array as evaluated.

func (ValidationContext) EvaluatedProp

func (ctx ValidationContext) EvaluatedProp(prop string)

EvaluatedProp marks given property of object as evaluated.

func (ValidationContext) Validate

func (ctx ValidationContext) Validate(s *Schema, spath string, v interface{}, vpath string) error

Validate validates schema s with value v. Extension must use this method instead of *Schema.ValidateInterface method. This will be useful in implementing keywords like allOf/oneOf

spath is relative-json-pointer to s vpath is relative-json-pointer to v.

type ValidationError

type ValidationError struct {
	KeywordLocation         string             // validation path of validating keyword or schema
	AbsoluteKeywordLocation string             // absolute location of validating keyword or schema
	InstanceLocation        string             // location of the json value within the instance being validated
	Message                 string             // describes error
	Causes                  []*ValidationError // nested validation errors
}

ValidationError is the error type returned by Validate.

func (*ValidationError) Error

func (ve *ValidationError) Error() string

func (*ValidationError) GoString

func (ve *ValidationError) GoString() string

func (ValidationError) Group

func (ValidationError) Group(parent *ValidationError, causes ...error) error

Group is used by extensions to group multiple errors as causes to parent error. This is useful in implementing keywords like allOf where each schema specified in allOf can result a validationError.

Jump to

Keyboard shortcuts

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