jsonschema

package module
v1.0.0 Latest Latest
Warning

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

Go to latest
Published: Aug 25, 2026 License: MIT Imports: 26 Imported by: 0

README

json-schema

CI CodeQL Coverage Mutation Documentation Go Reference Release Go License

json-schema is an exact-number, dialect-aware JSON Schema compiler and validator for Go. It supports Draft 3, Draft 4, Draft 6, Draft 7, Draft 2019-09, and Draft 2020-12 without implicit network access or global mutable registries.

The pinned official suite currently passes 8,505 cases across 354 mandatory and optional fixture files with zero skips and zero failures. This is executable compatibility evidence, not by itself a v1.0.0 release claim. The stable v1 module remains subject to every gate in Conformance and Releasing is satisfied.

The minimum supported toolchain is Go 1.26.6.

Quick start

compiler, err := jsonschema.NewCompiler(
    jsonschema.WithDialect(jsonschema.Draft202012),
)
if err != nil {
    return err
}

schema, err := compiler.Compile(
    context.Background(),
    []byte(`{"type":"object","required":["name"],"properties":{"name":{"type":"string"}}}`),
)
if err != nil {
    return err
}

result, err := schema.Validate(
    context.Background(),
    []byte(`{"name":"Ada"}`),
)
if err != nil {
    return err
}
fmt.Println(result.Valid) // true

Compilation validates the schema against the embedded official meta-schema. Compiled schemas are immutable and reusable concurrently. Validate accepts raw JSON; ValidateValue accepts Go values and preserves json.Number text. ValidateOutput and ValidateValueOutput provide Flag, Basic, Detailed, and Verbose output units. CollectAnnotations returns retained successful-path annotations as a flat deterministic list.

Format keywords are annotations by default; enable recognized assertions with WithFormatAssertion. Content keywords are annotations by default, and WithContentAssertion enables only Draft 7's optional assertion behavior. Draft 2019-09 and Draft 2020-12 content processing never changes the enclosing schema result. Remote references require an explicit ResourceLoader; the core never performs network I/O.

Contracts

Development

make check runs formatting, module, vet, tests, fixture provenance, conformance-manifest, and Bowtie protocol gates offline after dependencies are available. go test -race ./... is the concurrency gate. See CONTRIBUTING.md for fixture and behavior changes.

License

MIT. See LICENSE and NOTICE.

Ecosystem

Use the Golib documentation portal to choose companion packages, supported stacks, recipes, and operations guidance.

Documentation

Overview

Package jsonschema compiles and evaluates JSON Schemas without implicit network access.

Dialect selection, schema retrieval, extension registries, format policy, output shape, and resource limits are explicit compiler configuration. A compiled schema is immutable and safe for concurrent use.

The implementation is under active development. Compliance claims are made only by the generated conformance evidence committed with the module.

Example
package main

import (
	"context"
	"fmt"

	jsonschema "github.com/faustbrian/go-json-schema"
)

func main() {
	compiler, _ := jsonschema.NewCompiler(
		jsonschema.WithDialect(jsonschema.Draft202012),
	)
	schema, _ := compiler.Compile(
		context.Background(),
		[]byte(`{"type":"integer","minimum":1}`),
	)

	result, _ := schema.Validate(context.Background(), []byte(`2`))
	fmt.Println(result.Valid)

}
Output:
true

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidJSON classifies malformed or ambiguous JSON input.
	ErrInvalidJSON = errors.New("invalid JSON")
	// ErrInvalidSchema classifies schemas that are invalid for their dialect.
	ErrInvalidSchema = errors.New("invalid schema")
	// ErrLimitExceeded classifies work rejected by an explicit resource limit.
	ErrLimitExceeded = errors.New("resource limit exceeded")
	// ErrResourceUnavailable classifies a schema resource that could not be loaded.
	ErrResourceUnavailable = errors.New("schema resource unavailable")
	// ErrResourceNotFound classifies an identifier absent from a loader.
	ErrResourceNotFound = errors.New("schema resource not found")
	// ErrUnsupportedDialect classifies an unknown stable dialect.
	ErrUnsupportedDialect = errors.New("unsupported dialect")
	// ErrUnsupportedVocabulary classifies an unknown required vocabulary.
	ErrUnsupportedVocabulary = errors.New("unsupported vocabulary")
	// ErrCallbackPanic classifies a recovered application callback panic.
	ErrCallbackPanic = errors.New("callback panic")
)

Functions

This section is empty.

Types

type Compiler

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

Compiler owns immutable dialect and resource policy used during compilation.

func NewCompiler

func NewCompiler(options ...Option) (*Compiler, error)

NewCompiler constructs an isolated compiler. Draft 2020-12 is the explicit default when no dialect option is supplied.

func (*Compiler) Compile

func (compiler *Compiler) Compile(ctx context.Context, raw []byte) (*Schema, error)

Compile parses and compiles one schema document using the configured loader.

type CompositeLoader

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

CompositeLoader tries loaders in order and falls through only when a loader classifies the resource as not found.

func NewCompositeLoader

func NewCompositeLoader(loaders ...ResourceLoader) (*CompositeLoader, error)

NewCompositeLoader constructs an immutable ordered loader chain.

func (*CompositeLoader) Load

func (loader *CompositeLoader) Load(ctx context.Context, identifier string) ([]byte, error)

Load implements ResourceLoader.

type Dialect

type Dialect string

Dialect identifies a released JSON Schema Core and Validation dialect.

const (
	// Draft3 identifies JSON Schema Draft 3.
	Draft3 Dialect = "http://json-schema.org/draft-03/schema#"
	// Draft4 identifies JSON Schema Draft 4.
	Draft4 Dialect = "http://json-schema.org/draft-04/schema#"
	// Draft6 identifies JSON Schema Draft 6.
	Draft6 Dialect = "http://json-schema.org/draft-06/schema#"
	// Draft7 identifies JSON Schema Draft 7.
	Draft7 Dialect = "http://json-schema.org/draft-07/schema#"
	// Draft201909 identifies JSON Schema Draft 2019-09.
	Draft201909 Dialect = "https://json-schema.org/draft/2019-09/schema"
	// Draft202012 identifies JSON Schema Draft 2020-12.
	Draft202012 Dialect = "https://json-schema.org/draft/2020-12/schema"
)

type FSLoader

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

FSLoader confines hierarchical resource identifiers to a caller-provided filesystem rooted at one absolute base URI.

func NewFSLoader

func NewFSLoader(baseIdentifier string, filesystem fs.FS) (*FSLoader, error)

NewFSLoader constructs a confined filesystem loader.

func (*FSLoader) Load

func (loader *FSLoader) Load(ctx context.Context, identifier string) ([]byte, error)

Load implements ResourceLoader without permitting authority or path escape.

type FormatChecker

type FormatChecker interface {
	Valid(context.Context, string) (bool, error)
}

FormatChecker validates the string representation of a named format.

type FormatFunc

type FormatFunc func(context.Context, string) (bool, error)

FormatFunc adapts a function to FormatChecker.

func (FormatFunc) Valid

func (format FormatFunc) Valid(ctx context.Context, value string) (bool, error)

Valid implements FormatChecker.

type JSONError

type JSONError struct {
	Offset int64
	Kind   error
	Cause  error
}

JSONError describes a JSON ingestion failure without retaining input bytes.

func (*JSONError) Error

func (err *JSONError) Error() string

Error implements error.

func (*JSONError) Unwrap

func (err *JSONError) Unwrap() []error

Unwrap exposes both the classification and underlying cause.

type KeywordCompiler

type KeywordCompiler interface {
	Compile(context.Context, Dialect, Value) (KeywordEvaluator, error)
}

KeywordCompiler compiles one keyword value into an immutable evaluator.

type KeywordCompilerFunc

type KeywordCompilerFunc func(context.Context, Dialect, Value) (KeywordEvaluator, error)

KeywordCompilerFunc adapts a function to KeywordCompiler.

func (KeywordCompilerFunc) Compile

func (compiler KeywordCompilerFunc) Compile(
	ctx context.Context,
	dialect Dialect,
	value Value,
) (KeywordEvaluator, error)

Compile implements KeywordCompiler.

type KeywordEvaluator

type KeywordEvaluator interface {
	Evaluate(context.Context, Value) (KeywordResult, error)
}

KeywordEvaluator evaluates a compiled custom keyword.

type KeywordEvaluatorFunc

type KeywordEvaluatorFunc func(context.Context, Value) (KeywordResult, error)

KeywordEvaluatorFunc adapts a function to KeywordEvaluator.

func (KeywordEvaluatorFunc) Evaluate

func (evaluator KeywordEvaluatorFunc) Evaluate(
	ctx context.Context,
	value Value,
) (KeywordResult, error)

Evaluate implements KeywordEvaluator.

type KeywordResult

type KeywordResult struct {
	Valid      bool
	Annotation json.RawMessage
}

KeywordResult reports custom assertion validity and an optional exact JSON annotation. A nil Annotation means no annotation; use `json.RawMessage("null")` to annotate with JSON null.

type LimitError

type LimitError struct {
	Resource string
	Limit    int
}

LimitError reports which deterministic work budget was exhausted.

func (*LimitError) Error

func (err *LimitError) Error() string

Error implements error.

func (*LimitError) Unwrap

func (err *LimitError) Unwrap() error

Unwrap classifies the error as ErrLimitExceeded.

type Limits

type Limits struct {
	MaxInputBytes             int
	MaxNestingDepth           int
	MaxTotalValues            int
	MaxObjectMembers          int
	MaxArrayItems             int
	MaxNumberBytes            int
	MaxSchemaResources        int
	MaxTotalSchemaBytes       int
	MaxEvaluationOps          int
	MaxUniqueComparisons      int
	MaxFormatChecks           int
	MaxSchemaNodes            int
	MaxReferenceDepth         int
	MaxDynamicScopeDepth      int
	MaxCombinatorBranches     int
	MaxRegexCount             int
	MaxRegexBytes             int
	MaxRegexBacktracking      int
	MaxRegexMatchMilliseconds int
	MaxOutputUnits            int
	MaxCustomKeywordCompiles  int
	MaxCustomKeywordCalls     int
	MaxAnnotationBytes        int
}

Limits bounds JSON ingestion work. Additional compile and evaluation limits will be added as their corresponding evaluator components are introduced.

func DefaultLimits

func DefaultLimits() Limits

DefaultLimits returns conservative standalone defaults.

type MapLoader

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

MapLoader is an immutable in-memory schema resource loader.

Example
package main

import (
	"context"
	"fmt"

	jsonschema "github.com/faustbrian/go-json-schema"
)

func main() {
	loader, _ := jsonschema.NewMapLoader(map[string][]byte{
		"https://schemas.example.test/name": []byte(`{
			"$id":"https://schemas.example.test/name",
			"type":"string",
			"minLength":1
		}`),
	})
	compiler, _ := jsonschema.NewCompiler(jsonschema.WithResourceLoader(loader))
	schema, _ := compiler.Compile(
		context.Background(),
		[]byte(`{"$ref":"https://schemas.example.test/name"}`),
	)

	result, _ := schema.Validate(context.Background(), []byte(`"Ada"`))
	fmt.Println(result.Valid)

}
Output:
true

func NewMapLoader

func NewMapLoader(resources map[string][]byte) (*MapLoader, error)

NewMapLoader copies a set of resources into an immutable loader.

func (*MapLoader) Load

func (loader *MapLoader) Load(ctx context.Context, identifier string) ([]byte, error)

Load implements ResourceLoader and returns caller-owned bytes.

type Option

type Option func(*compilerConfig) error

Option configures a Compiler without mutating shared global state.

func WithContentAssertion

func WithContentAssertion() Option

WithContentAssertion enables Draft 7 validation of recognized content encodings and media types. Later dialects keep content as annotations.

func WithDialect

func WithDialect(dialect Dialect) Option

WithDialect selects the dialect used to compile schemas.

func WithFormat

func WithFormat(name string, checker FormatChecker) Option

WithFormat registers or replaces one compiler-owned format checker.

func WithFormatAssertion

func WithFormatAssertion() Option

WithFormatAssertion enables format validation for recognized formats.

func WithLimits

func WithLimits(limits Limits) Option

WithLimits replaces the compiler's resource limits.

func WithResourceLoader

func WithResourceLoader(loader ResourceLoader) Option

WithResourceLoader authorizes explicit schema retrieval during compilation.

func WithVocabulary

func WithVocabulary(
	identifier string,
	keywords map[string]KeywordCompiler,
) Option

WithVocabulary registers one instance-owned custom vocabulary.

type OutputFormat

type OutputFormat string

OutputFormat selects one of the standard JSON Schema output forms.

const (
	// OutputFlag emits only the overall validity flag.
	OutputFlag OutputFormat = "flag"
	// OutputBasic emits a flat list of errors or annotations.
	OutputBasic OutputFormat = "basic"
	// OutputDetailed emits location-aware nested validation results.
	OutputDetailed OutputFormat = "detailed"
	// OutputVerbose emits the complete location-aware validation result tree.
	OutputVerbose OutputFormat = "verbose"
)

type OutputUnit

type OutputUnit struct {
	Valid                   bool         `json:"valid"`
	KeywordLocation         string       `json:"keywordLocation"`
	AbsoluteKeywordLocation string       `json:"absoluteKeywordLocation,omitempty"`
	InstanceLocation        string       `json:"instanceLocation"`
	Error                   string       `json:"error,omitempty"`
	Errors                  []OutputUnit `json:"errors,omitempty"`
	Annotations             []OutputUnit `json:"annotations,omitempty"`
	Annotation              any          `json:"annotation,omitempty"`
	// contains filtered or unexported fields
}

OutputUnit is one unit in a standard JSON Schema validation output.

func (OutputUnit) MarshalJSON

func (unit OutputUnit) MarshalJSON() ([]byte, error)

MarshalJSON emits the compact standard representation selected for the root output unit.

type ResourceLoader

type ResourceLoader interface {
	Load(context.Context, string) ([]byte, error)
}

ResourceLoader retrieves an explicitly authorized schema resource.

type ResourceLoaderFunc

type ResourceLoaderFunc func(context.Context, string) ([]byte, error)

ResourceLoaderFunc adapts a function to ResourceLoader.

func (ResourceLoaderFunc) Load

func (loader ResourceLoaderFunc) Load(ctx context.Context, identifier string) ([]byte, error)

Load implements ResourceLoader.

type Result

type Result struct {
	Valid bool `json:"valid"`
}

Result is the minimum flag output from an evaluation.

type Schema

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

Schema is an immutable evaluation plan safe for concurrent validation.

func (*Schema) CollectAnnotations

func (schema *Schema) CollectAnnotations(
	ctx context.Context,
	raw []byte,
) ([]OutputUnit, error)

CollectAnnotations validates raw JSON and returns the retained annotation results as a flat, deterministic list. Failed schema branches do not contribute annotations.

func (*Schema) Validate

func (schema *Schema) Validate(ctx context.Context, raw []byte) (Result, error)

Validate parses and evaluates a raw JSON instance.

func (*Schema) ValidateOutput

func (schema *Schema) ValidateOutput(
	ctx context.Context,
	raw []byte,
	format OutputFormat,
) (OutputUnit, error)

ValidateOutput validates raw JSON and returns the selected standard output.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"

	jsonschema "github.com/faustbrian/go-json-schema"
)

func main() {
	compiler, _ := jsonschema.NewCompiler()
	schema, _ := compiler.Compile(context.Background(), []byte(`{"type":"string"}`))

	output, _ := schema.ValidateOutput(
		context.Background(),
		[]byte(`42`),
		jsonschema.OutputFlag,
	)
	encoded, _ := json.Marshal(output)
	fmt.Println(string(encoded))

}
Output:
{"valid":false}

func (*Schema) ValidateValue

func (schema *Schema) ValidateValue(ctx context.Context, value any) (Result, error)

ValidateValue validates a caller-provided value after bounded JSON encoding. Integer types and json.Number retain exact decimal semantics.

Example
package main

import (
	"context"
	"encoding/json"
	"fmt"

	jsonschema "github.com/faustbrian/go-json-schema"
)

func main() {
	compiler, _ := jsonschema.NewCompiler()
	schema, _ := compiler.Compile(
		context.Background(),
		[]byte(`{"type":"number","multipleOf":0.1}`),
	)

	result, _ := schema.ValidateValue(context.Background(), json.Number("0.3"))
	fmt.Println(result.Valid)

}
Output:
true

func (*Schema) ValidateValueOutput

func (schema *Schema) ValidateValueOutput(
	ctx context.Context,
	value any,
	format OutputFormat,
) (OutputUnit, error)

ValidateValueOutput validates a caller-provided value and returns the selected standard output form.

type Value

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

Value is a read-only view of an exact schema or instance JSON value.

func (Value) Bool

func (value Value) Bool() (bool, bool)

Bool returns a boolean value and whether the kind matched.

func (Value) Index

func (value Value) Index(index int) (Value, bool)

Index returns one array item.

func (Value) Kind

func (value Value) Kind() ValueKind

Kind returns the JSON value kind.

func (Value) Len

func (value Value) Len() int

Len returns the array item or object member count, or zero otherwise.

func (Value) Lookup

func (value Value) Lookup(name string) (Value, bool)

Lookup returns one object member.

func (Value) Names

func (value Value) Names() []string

Names returns a sorted copy of object member names.

func (Value) Number

func (value Value) Number() (string, bool)

Number returns the exact JSON number text and whether the kind matched.

func (Value) String

func (value Value) String() (string, bool)

String returns a string value and whether the kind matched.

type ValueKind

type ValueKind uint8

ValueKind identifies an immutable exact JSON value kind.

const (
	// NullKind identifies null or an absent Value.
	NullKind ValueKind = iota
	// BooleanKind identifies a JSON boolean.
	BooleanKind
	// NumberKind identifies an exact JSON number.
	NumberKind
	// StringKind identifies a JSON string.
	StringKind
	// ArrayKind identifies a JSON array.
	ArrayKind
	// ObjectKind identifies a JSON object.
	ObjectKind
)

Directories

Path Synopsis
cmd
bowtie-json-schema command
Command bowtie-json-schema implements the Bowtie harness protocol.
Command bowtie-json-schema implements the Bowtie harness protocol.
internal
cmd/conformance-manifest command
Command conformance-manifest generates pinned official-suite evidence.
Command conformance-manifest generates pinned official-suite evidence.

Jump to

Keyboard shortcuts

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