jsonschema

package module
v3.0.8 Latest Latest
Warning

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

Go to latest
Published: Apr 4, 2023 License: BSD-3-Clause Imports: 20 Imported by: 29

README

jsonschema v2.2.0

License GoDoc Go Report Card CircleCI Coverage Status

!!! WARNING !!!

This library is used internally at Ory and subject to rapid change.

!!! WARNING !!!

Package jsonschema provides json-schema compilation and validation.

This implementation of JSON Schema, supports draft4, draft6 and draft7.

Passes all tests(including optional) in https://github.com/json-schema/JSON-Schema-Test-Suite

An example of using this package:

schema, err := jsonschema.Compile("schemas/purchaseOrder.json")
if err != nil {
    return err
}
f, err := os.Open("purchaseOrder.json")
if err != nil {
    return err
}
defer f.Close()
if err = schema.Validate(f); err != nil {
    return err
}

The schema is compiled against the version specified in $schema property. If $schema property is missing, it uses latest draft which currently is draft7. You can force to use draft4 when $schema is missing, as follows:

compiler := jsonschema.NewCompiler()
compler.Draft = jsonschema.Draft4

you can also validate go value using schema.ValidateInterface(interface{}) method.
but the argument should not be user-defined struct.

This package supports loading json-schema from filePath and fileURL.

To load json-schema from HTTPURL, add following import:

import _ "github.com/ory/jsonschema/v2/httploader"

Loading from urls for other schemes (such as ftp), can be plugged in. see package jsonschema/httploader for an example

To load json-schema from in-memory:

data := `{"type": "string"}`
url := "sch.json"
compiler := jsonschema.NewCompiler()
if err := compiler.AddResource(url, strings.NewReader(data)); err != nil {
    return err
}
schema, err := compiler.Compile(url)
if err != nil {
    return err
}
f, err := os.Open("doc.json")
if err != nil {
    return err
}
defer f.Close()
if err = schema.Validate(f); err != nil {
    return err
}

This package supports json string formats:

  • date-time
  • date
  • time
  • hostname
  • email
  • ip-address
  • ipv4
  • ipv6
  • uri
  • uriref/uri-reference
  • regex
  • format
  • json-pointer
  • relative-json-pointer
  • uri-template (limited validation)

Developers can register their own formats by adding them to jsonschema.Formats map.

"base64" contentEncoding is supported. Custom decoders can be registered by adding them to jsonschema.Decoders map.

"application/json" contentMediaType is supported. Custom mediatypes can be registered by adding them to jsonschema.MediaTypes map.

ValidationError

The ValidationError returned by Validate method contains detailed context to understand why and where the error is.

schema.json:

{
      "$ref": "t.json#/definitions/employee"
}

t.json:

{
    "definitions": {
        "employee": {
            "type": "string"
        }
    }
}

doc.json:

1

Validating doc.json with schema.json, gives following ValidationError:

I[#] S[#] doesn't validate with "schema.json#"
  I[#] S[#/$ref] doesn't valide with "t.json#/definitions/employee"
    I[#] S[#/definitions/employee/type] expected string, but got number

Here I stands for instance document and S stands for schema document.
The json-fragments that caused error in instance and schema documents are represented using json-pointer notation.
Nested causes are printed with indent.

Custom Extensions

Custom Extensions can be registered as shown in extension_test.go

CLI

jv <schema-file> [<json-doc>]...

if no <json-doc> arguments are passed, it simply validates the <schema-file>.

exit-code is 1, if there are any validation errors

Documentation

Overview

Package jsonschema provides json-schema compilation and validation.

This implementation of JSON Schema, supports draft4, draft6 and draft7. Passes all tests(including optional) in https://github.com/json-schema/JSON-Schema-Test-Suite

An example of using this package:

schema, err := jsonschema.Compile("schemas/purchaseOrder.json")
if err != nil {
	return err
}
f, err := os.Open("purchaseOrder.json")
if err != nil {
	return err
}
defer f.Close()
if err = schema.Validate(f); err != nil {
	return err
}

The schema is compiled against the version specified in `$schema` property. If `$schema` property is missing, it uses latest draft which currently is draft7. You can force to use draft4 when `$schema` is missing, as follows:

compiler := jsonschema.NewCompiler()
compler.Draft = jsonschema.Draft4

you can also validate go value using schema.ValidateInterface(interface{}) method. but the argument should not be user-defined struct.

This package supports loading json-schema from filePath and fileURL.

To load json-schema from HTTPURL, add following import:

import _ "github.com/ory/jsonschema/v3/httploader"

Loading from urls for other schemes (such as ftp), can be plugged in. see package jsonschema/httploader for an example

To load json-schema from in-memory:

data := `{"type": "string"}`
url := "sch.json"
compiler := jsonschema.NewCompiler()
if err := compiler.AddResource(url, strings.NewReader(data)); err != nil {
	return err
}
schema, err := compiler.Compile(url)
if err != nil {
	return err
}
f, err := os.Open("doc.json")
if err != nil {
	return err
}
defer f.Close()
if err = schema.Validate(f); err != nil {
	return err
}

This package supports json string formats: date-time, date, time, hostname, email, ip-address, ipv4, ipv6, uri, uriref, regex, format, json-pointer, relative-json-pointer, uri-template (limited validation). Developers can register their own formats by adding them to jsonschema.Formats map.

"base64" contentEncoding is supported. Custom decoders can be registered by adding them to jsonschema.Decoders map.

"application/json" contentMediaType is supported. Custom mediatypes can be registered by adding them to jsonschema.MediaTypes map.

The ValidationError returned by Validate method contains detailed context to understand why and where the error is.

Custom Extensions can be registered as shown in extension_test.go

Index

Constants

This section is empty.

Variables

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 Draft4 = &Draft{id: "id", version: 4, url: "http://json-schema.org/draft-04/schema", data: `{
		"$schema": "http://json-schema.org/draft-04/schema#",
		"description": "Core schema meta-schema",
		"definitions": {
		    "schemaArray": {
		        "type": "array",
		        "minItems": 1,
		        "items": { "$ref": "#" }
		    },
		    "positiveInteger": {
		        "type": "integer",
		        "minimum": 0
		    },
		    "positiveIntegerDefault0": {
		        "allOf": [ { "$ref": "#/definitions/positiveInteger" }, { "default": 0 } ]
		    },
		    "simpleTypes": {
		        "enum": [ "array", "boolean", "integer", "null", "number", "object", "string" ]
		    },
		    "stringArray": {
		        "type": "array",
		        "items": { "type": "string" },
		        "minItems": 1,
		        "uniqueItems": true
		    }
		},
		"type": "object",
		"properties": {
		    "id": {
		        "type": "string",
		        "format": "uriref"
		    },
		    "$schema": {
		        "type": "string",
		        "format": "uri"
		    },
		    "title": {
		        "type": "string"
		    },
		    "description": {
		        "type": "string"
		    },
		    "default": {},
		    "multipleOf": {
		        "type": "number",
		        "minimum": 0,
		        "exclusiveMinimum": true
		    },
		    "maximum": {
		        "type": "number"
		    },
		    "exclusiveMaximum": {
		        "type": "boolean",
		        "default": false
		    },
		    "minimum": {
		        "type": "number"
		    },
		    "exclusiveMinimum": {
		        "type": "boolean",
		        "default": false
		    },
		    "maxLength": { "$ref": "#/definitions/positiveInteger" },
		    "minLength": { "$ref": "#/definitions/positiveIntegerDefault0" },
		    "pattern": {
		        "type": "string",
		        "format": "regex"
		    },
		    "additionalItems": {
		        "anyOf": [
		            { "type": "boolean" },
		            { "$ref": "#" }
		        ],
		        "default": {}
		    },
		    "items": {
		        "anyOf": [
		            { "$ref": "#" },
		            { "$ref": "#/definitions/schemaArray" }
		        ],
		        "default": {}
		    },
		    "maxItems": { "$ref": "#/definitions/positiveInteger" },
		    "minItems": { "$ref": "#/definitions/positiveIntegerDefault0" },
		    "uniqueItems": {
		        "type": "boolean",
		        "default": false
		    },
		    "maxProperties": { "$ref": "#/definitions/positiveInteger" },
		    "minProperties": { "$ref": "#/definitions/positiveIntegerDefault0" },
		    "required": { "$ref": "#/definitions/stringArray" },
		    "additionalProperties": {
		        "anyOf": [
		            { "type": "boolean" },
		            { "$ref": "#" }
		        ],
		        "default": {}
		    },
		    "definitions": {
		        "type": "object",
		        "additionalProperties": { "$ref": "#" },
		        "default": {}
		    },
		    "properties": {
		        "type": "object",
		        "additionalProperties": { "$ref": "#" },
		        "default": {}
		    },
		    "patternProperties": {
		        "type": "object",
		        "regexProperties": true,
		        "additionalProperties": { "$ref": "#" },
		        "default": {}
		    },
		    "regexProperties": { "type": "boolean" },
		    "dependencies": {
		        "type": "object",
		        "additionalProperties": {
		            "anyOf": [
		                { "$ref": "#" },
		                { "$ref": "#/definitions/stringArray" }
		            ]
		        }
		    },
		    "enum": {
		        "type": "array",
		        "minItems": 1,
		        "uniqueItems": true
		    },
		    "type": {
		        "anyOf": [
		            { "$ref": "#/definitions/simpleTypes" },
		            {
		                "type": "array",
		                "items": { "$ref": "#/definitions/simpleTypes" },
		                "minItems": 1,
		                "uniqueItems": true
		            }
		        ]
		    },
		    "allOf": { "$ref": "#/definitions/schemaArray" },
		    "anyOf": { "$ref": "#/definitions/schemaArray" },
		    "oneOf": { "$ref": "#/definitions/schemaArray" },
		    "not": { "$ref": "#" },
		    "format": { "type": "string" },
		    "$ref": { "type": "string" }
		},
		"dependencies": {
		    "exclusiveMaximum": [ "maximum" ],
		    "exclusiveMinimum": [ "minimum" ]
		},
		"default": {}
	}`}

Draft4 respresents http://json-schema.org/specification-links.html#draft-4

View Source
var Draft6 = &Draft{id: "$id", version: 6, url: "http://json-schema.org/draft-06/schema", data: `{
		"$schema": "http://json-schema.org/draft-06/schema#",
		"$id": "http://json-schema.org/draft-06/schema#",
		"title": "Core schema meta-schema",
		"definitions": {
			"schemaArray": {
				"type": "array",
				"minItems": 1,
				"items": { "$ref": "#" }
			},
			"nonNegativeInteger": {
				"type": "integer",
				"minimum": 0
			},
			"nonNegativeIntegerDefault0": {
				"allOf": [
					{ "$ref": "#/definitions/nonNegativeInteger" },
					{ "default": 0 }
				]
			},
			"simpleTypes": {
				"enum": [
					"array",
					"boolean",
					"integer",
					"null",
					"number",
					"object",
					"string"
				]
			},
			"stringArray": {
				"type": "array",
				"items": { "type": "string" },
				"uniqueItems": true,
				"default": []
			}
		},
		"type": ["object", "boolean"],
		"properties": {
			"$id": {
				"type": "string",
				"format": "uri-reference"
			},
			"$schema": {
				"type": "string",
				"format": "uri"
			},
			"$ref": {
				"type": "string",
				"format": "uri-reference"
			},
			"title": {
				"type": "string"
			},
			"description": {
				"type": "string"
			},
			"default": {},
			"multipleOf": {
				"type": "number",
				"exclusiveMinimum": 0
			},
			"maximum": {
				"type": "number"
			},
			"exclusiveMaximum": {
				"type": "number"
			},
			"minimum": {
				"type": "number"
			},
			"exclusiveMinimum": {
				"type": "number"
			},
			"maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
			"minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
			"pattern": {
				"type": "string",
				"format": "regex"
			},
			"additionalItems": { "$ref": "#" },
			"items": {
				"anyOf": [
					{ "$ref": "#" },
					{ "$ref": "#/definitions/schemaArray" }
				],
				"default": {}
			},
			"maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
			"minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
			"uniqueItems": {
				"type": "boolean",
				"default": false
			},
			"contains": { "$ref": "#" },
			"maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
			"minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
			"required": { "$ref": "#/definitions/stringArray" },
			"additionalProperties": { "$ref": "#" },
			"definitions": {
				"type": "object",
				"additionalProperties": { "$ref": "#" },
				"default": {}
			},
			"properties": {
				"type": "object",
				"additionalProperties": { "$ref": "#" },
				"default": {}
			},
			"patternProperties": {
				"type": "object",
				"regexProperties": true,
				"additionalProperties": { "$ref": "#" },
				"default": {}
			},
			"dependencies": {
				"type": "object",
				"additionalProperties": {
					"anyOf": [
						{ "$ref": "#" },
						{ "$ref": "#/definitions/stringArray" }
					]
				}
			},
			"propertyNames": { "$ref": "#" },
			"const": {},
			"enum": {
				"type": "array",
				"minItems": 1,
				"uniqueItems": true
			},
			"type": {
				"anyOf": [
					{ "$ref": "#/definitions/simpleTypes" },
					{
						"type": "array",
						"items": { "$ref": "#/definitions/simpleTypes" },
						"minItems": 1,
						"uniqueItems": true
					}
				]
			},
			"format": { "type": "string" },
			"allOf": { "$ref": "#/definitions/schemaArray" },
			"anyOf": { "$ref": "#/definitions/schemaArray" },
			"oneOf": { "$ref": "#/definitions/schemaArray" },
			"not": { "$ref": "#" }
		},
		"default": {}
	}`}

Draft6 respresents http://json-schema.org/specification-links.html#draft-6

View Source
var Draft7 = &Draft{id: "$id", version: 7, url: "http://json-schema.org/draft-07/schema", data: `{
		"$schema": "http://json-schema.org/draft-07/schema#",
		"$id": "http://json-schema.org/draft-07/schema#",
		"title": "Core schema meta-schema",
		"definitions": {
			"schemaArray": {
				"type": "array",
				"minItems": 1,
				"items": { "$ref": "#" }
			},
			"nonNegativeInteger": {
				"type": "integer",
				"minimum": 0
			},
			"nonNegativeIntegerDefault0": {
				"allOf": [
					{ "$ref": "#/definitions/nonNegativeInteger" },
					{ "default": 0 }
				]
			},
			"simpleTypes": {
				"enum": [
					"array",
					"boolean",
					"integer",
					"null",
					"number",
					"object",
					"string"
				]
			},
			"stringArray": {
				"type": "array",
				"items": { "type": "string" },
				"uniqueItems": true,
				"default": []
			}
		},
		"type": ["object", "boolean"],
		"properties": {
			"$id": {
				"type": "string",
				"format": "uri-reference"
			},
			"$schema": {
				"type": "string",
				"format": "uri"
			},
			"$ref": {
				"type": "string",
				"format": "uri-reference"
			},
			"$comment": {
				"type": "string"
			},
			"title": {
				"type": "string"
			},
			"description": {
				"type": "string"
			},
			"default": true,
			"readOnly": {
				"type": "boolean",
				"default": false
			},
			"examples": {
				"type": "array",
				"items": true
			},
			"multipleOf": {
				"type": "number",
				"exclusiveMinimum": 0
			},
			"maximum": {
				"type": "number"
			},
			"exclusiveMaximum": {
				"type": "number"
			},
			"minimum": {
				"type": "number"
			},
			"exclusiveMinimum": {
				"type": "number"
			},
			"maxLength": { "$ref": "#/definitions/nonNegativeInteger" },
			"minLength": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
			"pattern": {
				"type": "string",
				"format": "regex"
			},
			"additionalItems": { "$ref": "#" },
			"items": {
				"anyOf": [
					{ "$ref": "#" },
					{ "$ref": "#/definitions/schemaArray" }
				],
				"default": true
			},
			"maxItems": { "$ref": "#/definitions/nonNegativeInteger" },
			"minItems": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
			"uniqueItems": {
				"type": "boolean",
				"default": false
			},
			"contains": { "$ref": "#" },
			"maxProperties": { "$ref": "#/definitions/nonNegativeInteger" },
			"minProperties": { "$ref": "#/definitions/nonNegativeIntegerDefault0" },
			"required": { "$ref": "#/definitions/stringArray" },
			"additionalProperties": { "$ref": "#" },
			"definitions": {
				"type": "object",
				"additionalProperties": { "$ref": "#" },
				"default": {}
			},
			"properties": {
				"type": "object",
				"additionalProperties": { "$ref": "#" },
				"default": {}
			},
			"patternProperties": {
				"type": "object",
				"additionalProperties": { "$ref": "#" },
				"propertyNames": { "format": "regex" },
				"default": {}
			},
			"dependencies": {
				"type": "object",
				"additionalProperties": {
					"anyOf": [
						{ "$ref": "#" },
						{ "$ref": "#/definitions/stringArray" }
					]
				}
			},
			"propertyNames": { "$ref": "#" },
			"const": true,
			"enum": {
				"type": "array",
				"items": true,
				"minItems": 1,
				"uniqueItems": true
			},
			"type": {
				"anyOf": [
					{ "$ref": "#/definitions/simpleTypes" },
					{
						"type": "array",
						"items": { "$ref": "#/definitions/simpleTypes" },
						"minItems": 1,
						"uniqueItems": true
					}
				]
			},
			"format": { 
				"type": "string",
				"format": "format"
			},
			"contentMediaType": {
				"type": "string"
			},
			"contentEncoding": {
				"type": "string"
			},
			"if": {"$ref": "#"},
			"then": {"$ref": "#"},
			"else": {"$ref": "#"},
			"allOf": { "$ref": "#/definitions/schemaArray" },
			"anyOf": { "$ref": "#/definitions/schemaArray" },
			"oneOf": { "$ref": "#/definitions/schemaArray" },
			"not": { "$ref": "#" }
		},
		"default": true
	}`}

Draft7 respresents http://json-schema.org/specification-links.html#draft-7

View Source
var Formats = map[string]func(interface{}) bool{
	"date-time":             isDateTime,
	"date":                  isDate,
	"time":                  isTime,
	"hostname":              isHostname,
	"email":                 isEmail,
	"tel":                   isPhone,
	"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,
}

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(ctx context.Context, 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, SchemeNotRegisteredError(u.Scheme)

	}
	return loader(ctx, s)
}

LoadURL loads document at given 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(ctx context.Context, url string) (io.ReadCloser, error){
	"":     loadFile,
	"file": loadFileURL,
}

Loaders is a registry of functions, which know how to load 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

func DecodeJSON

func DecodeJSON(r io.Reader) (interface{}, error)

DecodeJSON decodes json document from r.

Note that number is decoded into json.Number instead of as a float64

Types

type Compiler

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

	// Extensions is used to register extensions.
	Extensions map[string]Extension

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

	// LoadURL loads the document at given URL.
	//
	// If nil, package global LoadURL is used.
	LoadURL func(ctx context.Context, s string) (io.ReadCloser, error)
	// contains filtered or unexported fields
}

A Compiler represents a json-schema compiler.

Currently draft4, draft6 and draft7 are supported

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(ctx context.Context, 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.

func (*Compiler) MustCompile

func (c *Compiler) MustCompile(ctx context.Context, 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.

type CompilerContext added in v3.0.1

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

CompilerContext provides additional context required in compiling for extension.

func (CompilerContext) Compile added in v3.0.1

func (ctx CompilerContext) Compile(c context.Context, v interface{}) (*Schema, error)

Compile compiles given value v into *Schema. This is useful in implementing keyword like allOf/oneOf

func (CompilerContext) CompileRef added in v3.0.1

func (ctx CompilerContext) CompileRef(c context.Context, ref string) (*Schema, error)

CompileRef compiles the schema referenced by ref uri

type Draft

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

A Draft represents json-schema draft

type Extension added in v3.0.1

type Extension struct {
	// Meta captures the metaschema for the new keywords.
	// This is used to validate the schema before calling Compile.
	Meta *Schema

	// Compile compiles the 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 func(ctx CompilerContext, m map[string]interface{}) (interface{}, error)

	// Validate validates the json value v with compiled representation s.
	// This is called only when compiled representation is not nil. Returned
	// error must be *ValidationError
	Validate func(ctx ValidationContext, s interface{}, v interface{}) error
}

Extension is used to define additional keywords to standard jsonschema. An extension can implement more than one keyword.

Extensions are registered in Compiler.Extensions map.

type InvalidJSONTypeError

type InvalidJSONTypeError string

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

func (InvalidJSONTypeError) Error

func (e InvalidJSONTypeError) Error() string

type Schema

type Schema struct {
	URL string // absolute url of the resource.
	Ptr string // json-pointer to schema. always starts with `#`.

	Format   string
	Always   *bool         // always pass/fail. used when booleans are used as schemas in draft-07.
	Ref      *Schema       // reference to actual schema. if not nil, all the remaining fields are ignored.
	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 false or *Schema.
	Dependencies         map[string]interface{} // value is *Schema or []string.

	// 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.
	Contains        *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.Float
	ExclusiveMinimum *big.Float
	Maximum          *big.Float
	ExclusiveMaximum *big.Float
	MultipleOf       *big.Float

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

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

A Schema represents compiled version of json-schema.

func Compile

func Compile(ctx context.Context, 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 added in v3.0.1

func CompileString(ctx context.Context, url, schema string) (*Schema, error)

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

func MustCompile

func MustCompile(ctx context.Context, 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 (*Schema) Validate

func (s *Schema) Validate(r io.Reader) error

Validate validates the given json data, against the json-schema.

Returned error can be *ValidationError.

func (*Schema) ValidateInterface

func (s *Schema) ValidateInterface(doc interface{}) (err error)

ValidateInterface validates given doc, against the json-schema.

the doc must be the value decoded by json package using interface{} type. we recommend to use jsonschema.DecodeJSON(io.Reader) to decode JSON.

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

type SchemeNotRegisteredError

type SchemeNotRegisteredError string

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

func (SchemeNotRegisteredError) Error

func (s SchemeNotRegisteredError) Error() string

type ValidationContext

type ValidationContext struct{}

ValidationContext provides additional context required in validating for extension.

func (ValidationContext) Error added in v3.0.1

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

Error used to construct validation error by extensions. schemaPtr is relative json pointer.

func (ValidationContext) Validate added in v3.0.1

func (ValidationContext) Validate(s *Schema, v interface{}) 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

type ValidationError

type ValidationError struct {
	// Message describes error
	Message string

	// InstancePtr is json-pointer which refers to json-fragment in json instance
	// that is not valid
	InstancePtr string

	// SchemaURL is the url to json-schema against which validation failed.
	// This is helpful, if your schema refers to external schemas
	SchemaURL string

	// SchemaPtr is json-pointer which refers to json-fragment in json schema
	// that failed to satisfy
	SchemaPtr string

	// Context represents error context for this specific validation error.
	Context ValidationErrorContext

	// Causes details the nested validation errors
	Causes []*ValidationError
}

ValidationError is the error type returned by Validate.

func (*ValidationError) Error

func (ve *ValidationError) Error() string

func (ValidationError) Group added in v3.0.1

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.

func (*ValidationError) MessageFmt

func (ve *ValidationError) MessageFmt() string

MessageFmt returns the Message formatted, but does not include child Cause messages.

type ValidationErrorContext added in v3.0.1

type ValidationErrorContext interface {
	AddContext(instancePtr, schemaPtr string)
	FinishInstanceContext()
}

ValidationErrorContext

type ValidationErrorContextRequired added in v3.0.1

type ValidationErrorContextRequired struct {
	// Missing contains JSON Pointers to all missing properties.
	Missing []string
}

ValidationErrorContextRequired is used as error context when one or more required properties are missing.

func (*ValidationErrorContextRequired) AddContext added in v3.0.1

func (r *ValidationErrorContextRequired) AddContext(instancePtr, _ string)

func (*ValidationErrorContextRequired) FinishInstanceContext added in v3.0.1

func (r *ValidationErrorContextRequired) FinishInstanceContext()

Directories

Path Synopsis
Package base64loader (standard encoding) implements loader.Loader for base64-encoded JSON url schemes.
Package base64loader (standard encoding) implements loader.Loader for base64-encoded JSON url schemes.
cmd
jv
Package fileloader implements loader.Loader for file url schemes.
Package fileloader implements loader.Loader for file url schemes.
Package httploader implements loader.Loader for http/https url.
Package httploader implements loader.Loader for http/https url.

Jump to

Keyboard shortcuts

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