package jsonschema
Import Path
github.com/santhosh-tekuri/jsonschema/v6 (on go.dev)
Dependency Relation
imports 25 packages, and imported by one package
Involved Source Files
compiler.go
content.go
draft.go
format.go
loader.go
objcompiler.go
output.go
position.go
root.go
roots.go
Package jsonschema provides json-schema compilation and validation.
The schema is compiled against the version specified in "$schema" property.
If "$schema" property is missing, it uses latest draft which currently implemented
by this library.
You can force to use specific draft, when "$schema" is missing, as follows:
compiler := jsonschema.NewCompiler()
compiler.DefaultDraft(jsonschema.Draft4)
This package supports loading json-schema from filePath and fileURL.
see examples for usage.
util.go
validator.go
vocab.go
Code Examples
package main
import (
"encoding/hex"
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
func main() {
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{"type": "string", "contentEncoding": "hex"}`))
if err != nil {
log.Fatal(err)
}
inst := "abcxyz"
c := jsonschema.NewCompiler()
c.RegisterContentEncoding(&jsonschema.Decoder{
Name: "hex",
Decode: hex.DecodeString,
})
c.AssertContent()
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"encoding/xml"
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
func main() {
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{"type": "string", "contentMediaType": "application/xml"}`))
if err != nil {
log.Fatal(err)
}
inst := "<abc></def>"
c := jsonschema.NewCompiler()
c.RegisterContentMediaType(&jsonschema.MediaType{
Name: "application/xml",
Validate: func(b []byte) error {
return xml.Unmarshal(b, new(any))
},
UnmarshalJSON: nil, // xml is not json-compatible format
})
c.AssertContent()
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
func main() {
validatePalindrome := func(v any) error {
s, ok := v.(string)
if !ok {
return nil
}
var runes []rune
for _, r := range s {
runes = append(runes, r)
}
for i, j := 0, len(runes)-1; i <= j; i, j = i+1, j-1 {
if runes[i] != runes[j] {
return fmt.Errorf("no match for rune at %d", i)
}
}
return nil
}
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{"type": "string", "format": "palindrome"}`))
if err != nil {
log.Fatal(err)
}
inst := "hello world"
c := jsonschema.NewCompiler()
c.RegisterFormat(&jsonschema.Format{
Name: "palindrome",
Validate: validatePalindrome,
})
c.AssertFormat()
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"fmt"
"log"
"strings"
"github.com/dlclark/regexp2"
"github.com/santhosh-tekuri/jsonschema/v6"
)
type dlclarkRegexp regexp2.Regexp
func (re *dlclarkRegexp) MatchString(s string) bool {
matched, err := (*regexp2.Regexp)(re).MatchString(s)
return err == nil && matched
}
func (re *dlclarkRegexp) String() string {
return (*regexp2.Regexp)(re).String()
}
func dlclarkCompile(s string) (jsonschema.Regexp, error) {
re, err := regexp2.Compile(s, regexp2.ECMAScript)
if err != nil {
return nil, err
}
return (*dlclarkRegexp)(re), nil
}
// Example_customRegexpEngine shows how to use dlclark/regexp2
// instead of regexp from standard library.
func main() {
// golang regexp does not support escape sequence: `\c`
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"type": "string",
"pattern": "^\\cc$"
}`))
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`"\u0003"`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
c.UseRegexpEngine(dlclarkCompile)
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"fmt"
"log"
"os"
"github.com/santhosh-tekuri/jsonschema/v6"
)
func main() {
schemaFile := "./testdata/examples/schema.json"
instanceFile := "./testdata/examples/instance.json"
c := jsonschema.NewCompiler()
sch, err := c.Compile(schemaFile)
if err != nil {
log.Fatal(err)
}
f, err := os.Open(instanceFile)
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(f)
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"crypto/tls"
"fmt"
"log"
"net/http"
"os"
"time"
"github.com/santhosh-tekuri/jsonschema/v6"
)
type HTTPURLLoader http.Client
func (l *HTTPURLLoader) Load(url string) (any, error) {
client := (*http.Client)(l)
resp, err := client.Get(url)
if err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
_ = resp.Body.Close()
return nil, fmt.Errorf("%s returned status code %d", url, resp.StatusCode)
}
defer resp.Body.Close()
return jsonschema.UnmarshalJSON(resp.Body)
}
func newHTTPURLLoader(insecure bool) *HTTPURLLoader {
httpLoader := HTTPURLLoader(http.Client{
Timeout: 15 * time.Second,
})
if insecure {
httpLoader.Transport = &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
}
return &httpLoader
}
func main() {
schemaURL := "https://raw.githubusercontent.com/santhosh-tekuri/boon/main/tests/examples/schema.json"
instanceFile := "./testdata/examples/instance.json"
loader := jsonschema.SchemeURLLoader{
"file": jsonschema.FileLoader{},
"http": newHTTPURLLoader(false),
"https": newHTTPURLLoader(false),
}
c := jsonschema.NewCompiler()
c.UseLoader(loader)
sch, err := c.Compile(schemaURL)
if err != nil {
log.Fatal(err)
}
f, err := os.Open(instanceFile)
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(f)
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
func main() {
catSchema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"type": "object",
"properties": {
"speak": { "const": "meow" }
},
"required": ["speak"]
}`))
if err != nil {
log.Fatal(err)
}
// note that dog.json is loaded from file ./testdata/examples/dog.json
petSchema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"oneOf": [
{ "$ref": "dog.json" },
{ "$ref": "cat.json" }
]
}`))
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`{"speak": "bow"}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
if err := c.AddResource("./testdata/examples/cat.json", catSchema); err != nil {
log.Fatal(err)
}
if err := c.AddResource("./testdata/examples/pet.json", petSchema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("./testdata/examples/pet.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"encoding/json"
"fmt"
"log"
"strconv"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
"golang.org/x/text/message"
)
// SchemaExt --
type ByteCount struct {
maxBytes *int
minBytes *int
}
func (s *ByteCount) Validate(ctx *jsonschema.ValidatorContext, v any) {
str, ok := v.(string)
if !ok {
return
}
if s.maxBytes != nil && len(str) > *s.maxBytes {
ctx.AddError(&MaxBytes{Got: len(str), Want: *s.maxBytes})
}
if s.minBytes != nil && len(str) < *s.minBytes {
ctx.AddError(&MinBytes{Got: len(str), Want: *s.maxBytes})
}
}
// Vocab --
func ByteCountVocab() *jsonschema.Vocabulary {
url := "http://example.com/meta/byte-count"
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties": {
"maxBytes": { "type": "integer", "minimum": 0 },
"minBytes": { "type": "integer", "minimum": 0 }
}
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
if err := c.AddResource(url, schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile(url)
if err != nil {
log.Fatal(err)
}
return &jsonschema.Vocabulary{
URL: url,
Schema: sch,
Compile: compileByteCount,
}
}
func numValue(obj map[string]any, prop string) *int {
v, ok := obj[prop]
if !ok {
return nil
}
switch v.(type) {
case json.Number, float32, float64, int, int8, int16, int32, int64, uint, uint8, uint16, uint32, uint64:
if n, err := strconv.Atoi(fmt.Sprint(v)); err == nil {
return &n
}
}
return nil
}
func compileByteCount(ctx *jsonschema.CompilerContext, obj map[string]any) (jsonschema.SchemaExt, error) {
max := numValue(obj, "maxBytes")
min := numValue(obj, "minBytes")
if max == nil && min == nil {
return nil, nil
}
return &ByteCount{maxBytes: max, minBytes: min}, nil
}
// ErrorKind --
type MaxBytes struct {
Got, Want int
}
func (*MaxBytes) KeywordPath() []string {
return []string{"maxBytes"}
}
func (k *MaxBytes) LocalizedString(p *message.Printer) string {
return p.Sprintf("maxBytes: got %d, want %d", k.Got, k.Want)
}
type MinBytes struct {
Got, Want int
}
func (*MinBytes) KeywordPath() []string {
return []string{"minBytes"}
}
func (k *MinBytes) LocalizedString(p *message.Printer) string {
return p.Sprintf("minBytes: got %d, want %d", k.Got, k.Want)
}
// Example --
func main() {
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties": {
"name": {
"type": "string",
"maxBytes": 5
}
}
}`))
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`
{ "name": "helloworld" }
`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
c.AssertVocabs()
c.RegisterVocabulary(ByteCountVocab())
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// SchemaExt --
type discriminator struct {
pname string
values map[string]*jsonschema.Schema
}
func (d *discriminator) Validate(ctx *jsonschema.ValidatorContext, v any) {
obj, ok := v.(map[string]any)
if !ok {
return
}
pvalue, ok := obj[d.pname]
if !ok {
return
}
value, ok := pvalue.(string)
if !ok {
return
}
sch := d.values[value]
if sch == nil {
return
}
if err := ctx.Validate(sch, v, nil); err != nil {
ctx.AddErr(err)
} else {
ctx.EvaluatedProp(d.pname)
}
}
// Vocab --
func discriminatorVocab() *jsonschema.Vocabulary {
url := "http://example.com/meta/discriminator"
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties" : {
"discriminator": {
"type": "object",
"minProperties": 1,
"maxProperties": 1,
"patternProperties": {
".*": {
"type": "object",
"patternProperties": {
".*": {
"$ref": "https://json-schema.org/draft/2020-12/schema"
}
}
}
}
}
}
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
if err := c.AddResource(url, schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile(url)
if err != nil {
log.Fatal(err)
}
return &jsonschema.Vocabulary{
URL: url,
Schema: sch,
Subschemas: []jsonschema.SchemaPath{
{jsonschema.Prop("discriminator"), jsonschema.AllProp{}, jsonschema.AllProp{}},
},
Compile: compileDiscriminator,
}
}
func compileDiscriminator(ctx *jsonschema.CompilerContext, obj map[string]any) (jsonschema.SchemaExt, error) {
v, ok := obj["discriminator"]
if !ok {
return nil, nil
}
d, ok := v.(map[string]any)
if !ok {
return nil, nil
}
var pname string
var pvalue any
for key, value := range d {
pname = key
pvalue = value
break
}
values := map[string]*jsonschema.Schema{}
vm, ok := pvalue.(map[string]any)
if !ok {
return nil, nil
}
for value := range vm {
values[value] = ctx.Enqueue([]string{"discriminator", pname, value})
}
return &discriminator{pname, values}, nil
}
// Example --
func main() {
// if kind is fish, swimmingSpeed is required
// if kind is dog, runningSpeed is required
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"type": "object",
"properties": {
"kind": { "type": "string" }
},
"required": ["kind"],
"discriminator": {
"kind": {
"fish": {
"type": "object",
"properties": {
"swimmingSpeed": { "type": "number" }
},
"required": ["swimmingSpeed"]
},
"dog": {
"type": "object",
"properties": {
"runningSpeed": { "type": "number" }
},
"required": ["runningSpeed"]
}
}
}
}`))
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"kind": "fish",
"runningSpeed": 5
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
c.AssertVocabs()
c.RegisterVocabulary(discriminatorVocab())
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
)
// SchemaExt --
type openapiDiscriminator struct {
pname string
mapping map[string]*jsonschema.Schema
}
func (d *openapiDiscriminator) Validate(ctx *jsonschema.ValidatorContext, v any) {
obj, ok := v.(map[string]any)
if !ok {
return
}
pvalue, ok := obj[d.pname]
if !ok {
return
}
value, ok := pvalue.(string)
if !ok {
return
}
sch := d.mapping[value]
if sch == nil {
return
}
if err := ctx.Validate(sch, v, nil); err != nil {
ctx.AddErr(err)
} else {
ctx.EvaluatedProp(d.pname)
}
}
// Vocab --
func openapiDiscriminatorVocab() *jsonschema.Vocabulary {
url := "http://example.com/meta/openapi/discriminator"
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties" : {
"discriminator": {
"type": "object",
"required": ["propertyName", "mapping"],
"properties": {
"propertyName": { "type": "string" },
"mapping": {
"type": "object",
"patternProperties": {
".*": { "type": "string" }
}
}
}
}
}
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
if err := c.AddResource(url, schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile(url)
if err != nil {
log.Fatal(err)
}
return &jsonschema.Vocabulary{
URL: url,
Schema: sch,
Subschemas: []jsonschema.SchemaPath{
{jsonschema.Prop("discriminator"), jsonschema.AllProp{}, jsonschema.AllProp{}},
},
Compile: compileOpenapiDiscriminator,
}
}
func compileOpenapiDiscriminator(ctx *jsonschema.CompilerContext, obj map[string]any) (jsonschema.SchemaExt, error) {
v, ok := obj["discriminator"]
if !ok {
return nil, nil
}
d, ok := v.(map[string]any)
if !ok {
return nil, nil
}
pname := d["propertyName"].(string)
mapping := map[string]*jsonschema.Schema{}
for val, ref := range d["mapping"].(map[string]any) {
sch, err := ctx.EnqueueRef(ref.(string))
if err != nil {
return nil, err
}
mapping[val] = sch
}
return &openapiDiscriminator{pname, mapping}, nil
}
// Example --
func main() {
// if kind is fish, swimmingSpeed is required
// if kind is dog, runningSpeed is required
openapiDoc, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"components": {
"schemas": {
"dog": {
"type": "object",
"properties": {
"runningSpeed": { "type": "number" }
},
"required": ["runningSpeed"]
},
"fish": {
"type": "object",
"properties": {
"swimmingSpeed": { "type": "number" }
},
"required": ["swimmingSpeed"]
},
"Pet": {
"type": "object",
"properties": {
"kind": { "type": "string" }
},
"required": ["kind"],
"discriminator": {
"propertyName": "kind",
"mapping": {
"fish": "#/components/schemas/fish",
"dog": "#/components/schemas/dog"
}
}
}
}
}
}`))
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"kind": "fish",
"runningSpeed": 5
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
c.AssertVocabs()
c.RegisterVocabulary(openapiDiscriminatorVocab())
if err := c.AddResource("openapidoc.json", openapiDoc); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("openapidoc.json#/components/schemas/Pet")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
package main
import (
"fmt"
"log"
"strings"
"github.com/santhosh-tekuri/jsonschema/v6"
"golang.org/x/text/message"
)
// SchemaExt --
type uniqueKeys struct {
pname string
}
func (s *uniqueKeys) Validate(ctx *jsonschema.ValidatorContext, v any) {
arr, ok := v.([]any)
if !ok {
return
}
var keys []any
for _, item := range arr {
obj, ok := item.(map[string]any)
if !ok {
continue
}
key, ok := obj[s.pname]
if ok {
keys = append(keys, key)
}
}
i, j, err := ctx.Duplicates(keys)
if err != nil {
ctx.AddErr(err)
return
}
if i != -1 {
ctx.AddError(&UniqueKeys{Key: s.pname, Duplicates: []int{i, j}})
}
}
// Vocab --
func uniqueKeysVocab() *jsonschema.Vocabulary {
url := "http://example.com/meta/unique-keys"
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"properties": {
"uniqueKeys": { "type": "string" }
}
}`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
if err := c.AddResource(url, schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile(url)
if err != nil {
log.Fatal(err)
}
return &jsonschema.Vocabulary{
URL: url,
Schema: sch,
Compile: compileUniqueKeys,
}
}
func compileUniqueKeys(ctx *jsonschema.CompilerContext, obj map[string]any) (jsonschema.SchemaExt, error) {
v, ok := obj["uniqueKeys"]
if !ok {
return nil, nil
}
s, ok := v.(string)
if !ok {
return nil, nil
}
return &uniqueKeys{pname: s}, nil
}
// ErrorKind --
type UniqueKeys struct {
Key string
Duplicates []int
}
func (*UniqueKeys) KeywordPath() []string {
return []string{"uniqueKeys"}
}
func (k *UniqueKeys) LocalizedString(p *message.Printer) string {
return p.Sprintf("items at %d and %d have same %s", k.Duplicates[0], k.Duplicates[1], k.Key)
}
// Example --
func main() {
schema, err := jsonschema.UnmarshalJSON(strings.NewReader(`{
"uniqueKeys": "id"
}`))
if err != nil {
log.Fatal(err)
}
inst, err := jsonschema.UnmarshalJSON(strings.NewReader(`[
{ "id": 1, "name": "alice" },
{ "id": 2, "name": "bob" },
{ "id": 1, "name": "scott" }
]`))
if err != nil {
log.Fatal(err)
}
c := jsonschema.NewCompiler()
c.AssertVocabs()
c.RegisterVocabulary(uniqueKeysVocab())
if err := c.AddResource("schema.json", schema); err != nil {
log.Fatal(err)
}
sch, err := c.Compile("schema.json")
if err != nil {
log.Fatal(err)
}
err = sch.Validate(inst)
fmt.Println("valid:", err == nil)
}
Package-Level Type Names (total 47)
AllItem : Position
AllProp : Position
Compiler compiles json schema into *Schema.
AddResource adds schema resource which gets used later in reference
resolution.
The argument url can be file path or url. Any fragment in url is ignored.
The argument doc must be valid json value.
AssertContent enables content assertions.
Content assertions include keywords:
- contentEncoding
- contentMediaType
- contentSchema
Default behavior is always disabled.
AssertFormat always enables format assertions.
Default Behavior:
for draft-07: enabled.
for draft/2019-09: disabled unless metaschema says `format` vocabulary is required.
for draft/2020-12: disabled unless metaschema says `format-assertion` vocabulary is required.
AssertVocabs always enables user-defined vocabularies assertions.
Default Behavior:
for draft-07: enabled.
for draft/2019-09: disabled unless metaschema enables a vocabulary.
for draft/2020-12: disabled unless metaschema enables a vocabulary.
Compile compiles json-schema at given loc.
DefaultDraft overrides the draft used to
compile schemas without `$schema` field.
By default, this library uses the latest
draft supported.
The use of this option is HIGHLY encouraged
to ensure continued correct operation of your
schema. The current default value will not stay
the same overtime.
MustCompile is like [Compile] but panics if compilation fails.
It simplifies safe initialization of global variables holding
compiled schema.
RegisterContentEncoding registers custom contentEncoding.
NOTE: content assertions are disabled by default.
see [Compiler.AssertContent].
RegisterContentMediaType registers custom contentMediaType.
NOTE: content assertions are disabled by default.
see [Compiler.AssertContent].
RegisterFormat registers custom format.
NOTE:
- "regex" format can not be overridden
- format assertions are disabled for draft >= 2019-09
see [Compiler.AssertFormat]
RegisterVocabulary registers custom vocabulary.
NOTE:
- vocabularies are disabled for draft >= 2019-09
see [Compiler.AssertVocabs]
UseLoader overrides the default [URLLoader] used
to load schema resources.
UseRegexpEngine changes the regexp-engine used.
By default it uses regexp package from go standard
library.
NOTE: must be called before compiling any schemas.
func NewCompiler() *Compiler
CompilerContext provides helpers for
compiling a [Vocabulary].
(*CompilerContext) Enqueue(schPath []string) *Schema
(*CompilerContext) EnqueueRef(ref string) (*Schema, error)
Decoder specifies how to decode specific contentEncoding.
Decode given string to byte array.
Name of contentEncoding.
func (*Compiler).RegisterContentEncoding(d *Decoder)
A Draft represents json-schema specification.
String returns the specification url.
*Draft : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
*Draft : github.com/pandatix/go-abnf.ElemItf
*Draft : expvar.Var
*Draft : fmt.Stringer
func (*Compiler).DefaultDraft(d *Draft)
var Draft2019 *Draft
var Draft2020 *Draft
var Draft4 *Draft
var Draft6 *Draft
var Draft7 *Draft
Anchor string
Ptr1 string
Ptr2 string
URL string
(*DuplicateAnchorError) Error() string
*DuplicateAnchorError : error
ID string
Ptr1 string
Ptr2 string
URL string
(*DuplicateIDError) Error() string
*DuplicateIDError : error
( ErrorKind) KeywordPath() []string
( ErrorKind) LocalizedString(*message.Printer) string
*github.com/santhosh-tekuri/jsonschema/v6/kind.AdditionalItems
*github.com/santhosh-tekuri/jsonschema/v6/kind.AdditionalProperties
*github.com/santhosh-tekuri/jsonschema/v6/kind.AllOf
*github.com/santhosh-tekuri/jsonschema/v6/kind.AnyOf
*github.com/santhosh-tekuri/jsonschema/v6/kind.Const
*github.com/santhosh-tekuri/jsonschema/v6/kind.Contains
*github.com/santhosh-tekuri/jsonschema/v6/kind.ContentEncoding
*github.com/santhosh-tekuri/jsonschema/v6/kind.ContentMediaType
*github.com/santhosh-tekuri/jsonschema/v6/kind.ContentSchema
*github.com/santhosh-tekuri/jsonschema/v6/kind.Dependency
*github.com/santhosh-tekuri/jsonschema/v6/kind.DependentRequired
*github.com/santhosh-tekuri/jsonschema/v6/kind.Enum
*github.com/santhosh-tekuri/jsonschema/v6/kind.ExclusiveMaximum
*github.com/santhosh-tekuri/jsonschema/v6/kind.ExclusiveMinimum
*github.com/santhosh-tekuri/jsonschema/v6/kind.FalseSchema
*github.com/santhosh-tekuri/jsonschema/v6/kind.Format
*github.com/santhosh-tekuri/jsonschema/v6/kind.Group
*github.com/santhosh-tekuri/jsonschema/v6/kind.InvalidJsonValue
*github.com/santhosh-tekuri/jsonschema/v6/kind.MaxContains
*github.com/santhosh-tekuri/jsonschema/v6/kind.MaxItems
*github.com/santhosh-tekuri/jsonschema/v6/kind.Maximum
*github.com/santhosh-tekuri/jsonschema/v6/kind.MaxLength
*github.com/santhosh-tekuri/jsonschema/v6/kind.MaxProperties
*github.com/santhosh-tekuri/jsonschema/v6/kind.MinContains
*github.com/santhosh-tekuri/jsonschema/v6/kind.MinItems
*github.com/santhosh-tekuri/jsonschema/v6/kind.Minimum
*github.com/santhosh-tekuri/jsonschema/v6/kind.MinLength
*github.com/santhosh-tekuri/jsonschema/v6/kind.MinProperties
*github.com/santhosh-tekuri/jsonschema/v6/kind.MultipleOf
*github.com/santhosh-tekuri/jsonschema/v6/kind.Not
*github.com/santhosh-tekuri/jsonschema/v6/kind.OneOf
*github.com/santhosh-tekuri/jsonschema/v6/kind.Pattern
*github.com/santhosh-tekuri/jsonschema/v6/kind.PropertyNames
*github.com/santhosh-tekuri/jsonschema/v6/kind.RefCycle
*github.com/santhosh-tekuri/jsonschema/v6/kind.Reference
*github.com/santhosh-tekuri/jsonschema/v6/kind.Required
*github.com/santhosh-tekuri/jsonschema/v6/kind.Schema
*github.com/santhosh-tekuri/jsonschema/v6/kind.Type
*github.com/santhosh-tekuri/jsonschema/v6/kind.UniqueItems
func (*ValidatorContext).AddError(k ErrorKind)
func (*ValidatorContext).AddErrors(errors []*ValidationError, k ErrorKind)
FileLoader loads json file url.
( FileLoader) Load(url string) (any, error)
ToFile is helper method to convert file url to file path.
FileLoader : URLLoader
Flag is output format with simple boolean property valid.
Valid bool
func (*ValidationError).FlagOutput() *FlagOutput
Format defined specific format.
Name of format.
Validate checks if given value is of this format.
func (*Compiler).RegisterFormat(f *Format)
Item : Position
MediaType specified how to validate bytes against specific contentMediaType.
Name of contentMediaType.
UnmarshalJSON unmarshals bytes into json value.
This must be nil if this mediatype is not compatible
with json.
Validate checks whether bytes conform to this mediatype.
func (*Compiler).RegisterContentMediaType(mt *MediaType)
Kind ErrorKind
( OutputError) MarshalJSON() ([]byte, error)
( OutputError) String() string
OutputError : github.com/goccy/go-json.Marshaler
OutputError : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
OutputError : github.com/pandatix/go-abnf.ElemItf
OutputError : encoding/json/v2.Marshaler
OutputError : expvar.Var
OutputError : fmt.Stringer
AbsoluteKeywordLocation string
Error *OutputError
Errors []OutputUnit
InstanceLocation string
KeywordLocation string
Valid bool
func (*ValidationError).BasicOutput() *OutputUnit
func (*ValidationError).DetailedOutput() *OutputUnit
func (*ValidationError).LocalizedBasicOutput(p *message.Printer) *OutputUnit
func (*ValidationError).LocalizedDetailedOutput(p *message.Printer) *OutputUnit
Position tells possible tokens in json.
AllItem
AllProp
Item
Prop
SchemaPath
Prop : Position
Regexp is the representation of compiled regular expression.
MatchString reports whether the string s contains
any match of the regular expression.
( Regexp) String() string
*regexp.Regexp
Regexp : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
Regexp : github.com/pandatix/go-abnf.ElemItf
Regexp : expvar.Var
Regexp : fmt.Stringer
RegexpEngine parses a regular expression and returns,
if successful, a Regexp object that can be used to
match against text.
func (*Compiler).UseRegexpEngine(engine RegexpEngine)
Schema is the representation of a compiled
jsonschema.
// nil or bool or *Schema
// nil or bool or *Schema
AllOf []*Schema
Anchor string
AnyOf []*Schema
type agnostic --
// boolean schema
Comment string
Const *any
Contains *Schema
ContentEncoding *Decoder
ContentMediaType *MediaType
ContentSchema *Schema
Default *any
// value is []string or *Schema
DependentRequired map[string][]string
DependentSchemas map[string]*Schema
Deprecated bool
Description string
DraftVersion int
// "" if not specified
DynamicRef *DynamicRef
Else *Schema
Enum *Enum
Examples []any
ExclusiveMaximum *big.Rat
ExclusiveMinimum *big.Rat
Extensions []SchemaExt
Format *Format
ID string
If *Schema
// nil or []*Schema or *Schema
Items2020 *Schema
Location string
MaxContains *int
MaxItems *int
MaxLength *int
object --
number --
MinContains *int
array --
string --
MinProperties *int
Minimum *big.Rat
MultipleOf *big.Rat
Not *Schema
OneOf []*Schema
Pattern Regexp
PatternProperties map[Regexp]*Schema
PrefixItems []*Schema
Properties map[string]*Schema
PropertyNames *Schema
ReadOnly bool
RecursiveAnchor bool
RecursiveRef *Schema
Ref *Schema
Required []string
Then *Schema
annotations --
Types *Types
UnevaluatedItems *Schema
UnevaluatedProperties *Schema
UniqueItems bool
WriteOnly bool
(*Schema) Validate(v any) error
func (*Compiler).Compile(loc string) (*Schema, error)
func (*Compiler).MustCompile(loc string) *Schema
func (*CompilerContext).Enqueue(schPath []string) *Schema
func (*CompilerContext).EnqueueRef(ref string) (*Schema, error)
func (*ValidatorContext).Validate(sch *Schema, v any, vpath []string) error
SchemaExt is compled form of vocabulary.
Validate validates v against and errors if any are reported
to ctx.
SchemaPath tells where to look for subschema inside keyword.
( SchemaPath) String() string
SchemaPath : Position
SchemaPath : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
SchemaPath : github.com/pandatix/go-abnf.ElemItf
SchemaPath : expvar.Var
SchemaPath : fmt.Stringer
SchemeURLLoader delegates to other [URLLoaders]
based on url scheme.
( SchemeURLLoader) Load(url string) (any, error)
SchemeURLLoader : URLLoader
Types encapsulates list of json value types.
Add specified json type. If typ is
not valid json type it is ignored.
( Types) IsEmpty() bool
( Types) String() string
( Types) ToStrings() []string
Types : github.com/pancsta/asyncmachine-go/internal/nofmt.Stringer
Types : github.com/pandatix/go-abnf.ElemItf
Types : expvar.Var
Types : fmt.Stringer
URL string
Vocabulary string
(*UnsupportedVocabularyError) Error() string
*UnsupportedVocabularyError : error
URLLoader knows how to load json from given url.
Load loads json from given absolute url.
FileLoader
SchemeURLLoader
func (*Compiler).UseLoader(loader URLLoader)
holds nested errors
kind of error
location of the JSON value within the instance being validated.
absolute, dereferenced schema location.
The `Basic` structure, a flat list of output units.
The `Detailed` structure, based on the schema.
(*ValidationError) Error() string
The `Flag` output format, merely the boolean result.
(*ValidationError) GoString() string
(*ValidationError) LocalizedBasicOutput(p *message.Printer) *OutputUnit
(*ValidationError) LocalizedDetailedOutput(p *message.Printer) *OutputUnit
(*ValidationError) LocalizedError(p *message.Printer) string
(*ValidationError) LocalizedGoString(p *message.Printer) string
*ValidationError : error
*ValidationError : fmt.GoStringer
func (*ValidatorContext).AddErrors(errors []*ValidationError, k ErrorKind)
ValidatorContext provides helpers for
validating with [SchemaExt].
AddErr reports the given err. This is typically used to report
the error created by subschema validation.
NOTE that err must be of type *ValidationError.
AddError reports validation-error of given kind.
AddErrors reports validation-errors of given kind.
(*ValidatorContext) Duplicates(arr []any) (int, int, error)
(*ValidatorContext) Equals(v1, v2 any) (bool, error)
EvaluatedItem marks items at given index of current array as evaluated.
EvaluatedProp marks given property of current object as evaluated.
Validate validates v with sch. vpath gives path of v from current context value.
ValueLocation returns location of value as jsonpath token array.
func SchemaExt.Validate(ctx *ValidatorContext, v any)
Vocabulary defines a set of keywords, their syntax and
their semantics.
Compile compiles the keywords(introduced by this vocabulary) in obj into [SchemaExt].
If obj does not contain any keywords introduced by this vocabulary, nil SchemaExt must
be returned.
Schema that is used to validate the keywords that is introduced by this
vocabulary.
Subschemas lists the possible locations of subschemas introduced by
this vocabulary.
URL identifier for this Vocabulary.
func (*Compiler).RegisterVocabulary(vocab *Vocabulary)
Package-Level Functions (total 3)
LocalizableError is an error whose message is localizable.
NewCompiler create Compiler Object.
UnmarshalJSON unmarshals into [any] without losing
number precision using [json.Number].
![]() |
The pages are generated with Golds v0.8.7. (GOOS=linux GOARCH=amd64) Golds is a Go 101 project developed by Tapir Liu. PR and bug reports are welcome and can be submitted to the issue list. Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds. |