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 ¶
- Variables
- type Compiler
- type CompositeLoader
- type Dialect
- type FSLoader
- type FormatChecker
- type FormatFunc
- type JSONError
- type KeywordCompiler
- type KeywordCompilerFunc
- type KeywordEvaluator
- type KeywordEvaluatorFunc
- type KeywordResult
- type LimitError
- type Limits
- type MapLoader
- type Option
- func WithContentAssertion() Option
- func WithDialect(dialect Dialect) Option
- func WithFormat(name string, checker FormatChecker) Option
- func WithFormatAssertion() Option
- func WithLimits(limits Limits) Option
- func WithResourceLoader(loader ResourceLoader) Option
- func WithVocabulary(identifier string, keywords map[string]KeywordCompiler) Option
- type OutputFormat
- type OutputUnit
- type ResourceLoader
- type ResourceLoaderFunc
- type Result
- type Schema
- func (schema *Schema) CollectAnnotations(ctx context.Context, raw []byte) ([]OutputUnit, error)
- func (schema *Schema) Validate(ctx context.Context, raw []byte) (Result, error)
- func (schema *Schema) ValidateOutput(ctx context.Context, raw []byte, format OutputFormat) (OutputUnit, error)
- func (schema *Schema) ValidateValue(ctx context.Context, value any) (Result, error)
- func (schema *Schema) ValidateValueOutput(ctx context.Context, value any, format OutputFormat) (OutputUnit, error)
- type Value
- func (value Value) Bool() (bool, bool)
- func (value Value) Index(index int) (Value, bool)
- func (value Value) Kind() ValueKind
- func (value Value) Len() int
- func (value Value) Lookup(name string) (Value, bool)
- func (value Value) Names() []string
- func (value Value) Number() (string, bool)
- func (value Value) String() (string, bool)
- type ValueKind
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 = 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 ¶
NewCompiler constructs an isolated compiler. Draft 2020-12 is the explicit default when no dialect option is supplied.
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.
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 ¶
NewFSLoader constructs a confined filesystem loader.
type FormatChecker ¶
FormatChecker validates the string representation of a named format.
type FormatFunc ¶
FormatFunc adapts a function to FormatChecker.
type KeywordCompiler ¶
type KeywordCompiler interface {
Compile(context.Context, Dialect, Value) (KeywordEvaluator, error)
}
KeywordCompiler compiles one keyword value into an immutable evaluator.
type KeywordCompilerFunc ¶
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 ¶
LimitError reports which deterministic work budget was exhausted.
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 ¶
NewMapLoader copies a set of resources into an immutable loader.
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 ¶
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 ¶
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 ¶
ResourceLoader retrieves an explicitly authorized schema resource.
type ResourceLoaderFunc ¶
ResourceLoaderFunc adapts a function to 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 ¶
CollectAnnotations validates raw JSON and returns the retained annotation results as a flat, deterministic list. Failed schema branches do not contribute annotations.
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 ¶
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.
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 )
Source Files
¶
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. |