jsonschema

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: May 31, 2025 License: MIT Imports: 24 Imported by: 36

README ΒΆ

JSON Schema Validator for Go

Go Version License Test Status

A high-performance JSON Schema validator for Go with direct struct validation, smart unmarshaling with defaults, and separated validation workflow.

Features

  • βœ… JSON Schema Draft 2020-12 - Full spec compliance
  • βœ… Direct Struct Validation - Zero-copy validation without JSON marshaling
  • βœ… Separated Workflow - Validation and unmarshaling as distinct operations
  • βœ… Type-Specific Methods - Optimized paths for JSON, structs, and maps
  • βœ… Schema References - Full $ref, $recursiveRef, $dynamicRef support
  • βœ… Custom Formats - Register your own validators
  • βœ… Internationalization - Multi-language error messages

Quick Start

Installation
go get github.com/kaptinlin/jsonschema
Basic Usage
import "github.com/kaptinlin/jsonschema"

// Compile schema
compiler := jsonschema.NewCompiler()
schema, err := compiler.Compile([]byte(`{
    "type": "object",
    "properties": {
        "name": {"type": "string", "minLength": 1},
        "age": {"type": "integer", "minimum": 0}
    },
    "required": ["name"]
}`))

// Recommended workflow: validate first, then unmarshal
data := []byte(`{"name": "John", "age": 25}`)

// Step 1: Validate
result := schema.Validate(data)
if result.IsValid() {
    fmt.Println("βœ… Valid")
    // Step 2: Unmarshal validated data
    var user User
    err := schema.Unmarshal(&user, data)
    if err != nil {
        log.Fatal(err)
    }
} else {
    fmt.Println("❌ Invalid")
    for field, err := range result.Errors {
        fmt.Printf("- %s: %s\n", field, err.Message)
    }
}
Type-Specific Validation

Choose the method that matches your data type for best performance:

// For JSON bytes - fastest JSON parsing
result := schema.ValidateJSON([]byte(`{"name": "John"}`))

// For Go structs - zero-copy validation
result := schema.ValidateStruct(Person{Name: "John"})

// For maps - optimal for pre-parsed data
result := schema.ValidateMap(map[string]interface{}{"name": "John"})

// Auto-detect input type
result := schema.Validate(anyData)
Unmarshal with Defaults
type User struct {
    Name    string `json:"name"`
    Country string `json:"country"`
    Active  bool   `json:"active"`
}

// Schema with defaults
schemaJSON := `{
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "country": {"type": "string", "default": "US"},
        "active": {"type": "boolean", "default": true}
    },
    "required": ["name"]
}`

schema, _ := compiler.Compile([]byte(schemaJSON))

// Validation + Unmarshal workflow
data := []byte(`{"name": "John"}`)
result := schema.Validate(data)
if result.IsValid() {
    var user User
    err := schema.Unmarshal(&user, data)
    // Result: user.Country = "US", user.Active = true
}

Advanced Features

Custom Formats
compiler.RegisterFormat("uuid", func(value string) bool {
    _, err := uuid.Parse(value)
    return err == nil
})

// Use in schema
schema := `{
    "type": "object",
    "properties": {
        "id": {"type": "string", "format": "uuid"}
    }
}`
Schema References
// Register reusable schemas
compiler.CompileWithID("person.json", personSchema)

// Reference in other schemas
schema := `{
    "type": "object",
    "properties": {
        "user": {"$ref": "person.json"}
    }
}`
Error Handling
import "errors" // Required for errors.As

// Detailed validation error handling
result := schema.Validate(data)
if !result.IsValid() {
    for field, err := range result.Errors {
        switch err.Keyword {
        case "required":
            fmt.Printf("Missing required field: %s\n", field)
        case "type":
            fmt.Printf("Invalid type for field: %s\n", field)
        default:
            fmt.Printf("%s: %s\n", field, err.Message)
        }
    }
}

// Unmarshal error handling
var user User
err := schema.Unmarshal(&user, data)
if err != nil {
    var unmarshalErr *jsonschema.UnmarshalError
    if errors.As(err, &unmarshalErr) {
        fmt.Printf("Error type: %s, Reason: %s\n", unmarshalErr.Type, unmarshalErr.Reason)
    }
}
Internationalization
i18n, _ := jsonschema.GetI18n()
localizer := i18n.NewLocalizer("zh-Hans")
result := schema.Validate(data)
localizedList := result.ToLocalizeList(localizer)

Validation + Unmarshal Patterns

Pattern 1: Strict Validation
result := schema.Validate(data)
if !result.IsValid() {
    return fmt.Errorf("validation failed: %v", result.Errors)
}

var user User
return schema.Unmarshal(&user, data)
Pattern 2: Conditional Processing
result := schema.Validate(data)
var user User
err := schema.Unmarshal(&user, data) // Always unmarshal

if result.IsValid() {
    // Process valid data
    return processUser(user)
} else {
    // Log errors but still process with defaults
    log.Printf("Validation warnings: %v", result.Errors)
    return processUserWithWarnings(user)
}
Pattern 3: Production Workflow
func ProcessUserData(schema *jsonschema.Schema, data []byte) error {
    // Step 1: Validate
    result := schema.Validate(data)
    if !result.IsValid() {
        return fmt.Errorf("validation failed: %v", result.Errors)
    }
    
    // Step 2: Unmarshal validated data
    var user User
    if err := schema.Unmarshal(&user, data); err != nil {
        return fmt.Errorf("unmarshal failed: %w", err)
    }
    
    // Step 3: Process user
    return saveUser(user)
}

Performance Optimization

Pre-compile Schemas
// Pre-compile for better performance
var userSchema, productSchema *jsonschema.Schema

func init() {
    compiler := jsonschema.NewCompiler()
    userSchema, _ = compiler.CompileWithID("user", userSchemaJSON)
    productSchema, _ = compiler.CompileWithID("product", productSchemaJSON)
}

// Reuse compiled schemas
func validateUser(data []byte) error {
    result := userSchema.ValidateJSON(data)
    if !result.IsValid() {
        return fmt.Errorf("validation failed")
    }
    return nil
}
Use Optimal Methods
// Choose the right method for your data type
schema.ValidateJSON(jsonBytes)    // Fastest for JSON
schema.ValidateStruct(structData) // Fastest for structs  
schema.ValidateMap(mapData)       // Fastest for maps

// Use high-performance JSON libraries
compiler.WithEncoderJSON(sonic.Marshal)
compiler.WithDecoderJSON(sonic.Unmarshal)

Documentation

Guides
Reference

Examples

See examples/ directory for working code samples:

Contributing

Contributions welcome! Please read CONTRIBUTING.md for guidelines.

License

MIT License - see LICENSE file for details.

πŸ™ Credits

Special thanks to:

Documentation ΒΆ

Overview ΒΆ

Credit to https://github.com/santhosh-tekuri/jsonschema

Index ΒΆ

Constants ΒΆ

This section is empty.

Variables ΒΆ

View Source
var (
	// ErrNoLoaderRegistered is returned when no loader is registered for the specified scheme.
	ErrNoLoaderRegistered = errors.New("no loader registered for scheme")

	// ErrFailedToReadData is returned when data cannot be read from the specified URL.
	ErrFailedToReadData = errors.New("failed to read data from URL")

	// ErrJSONUnmarshalError is returned when there is an error unmarshalling JSON.
	ErrJSONUnmarshalError = errors.New("json unmarshal error")

	// ErrXMLUnmarshalError is returned when there is an error unmarshalling XML.
	ErrXMLUnmarshalError = errors.New("xml unmarshal error")

	// ErrYAMLUnmarshalError is returned when there is an error unmarshalling YAML.
	ErrYAMLUnmarshalError = errors.New("yaml unmarshal error")

	// ErrFailedToFetch is returned when there is an error fetching from the URL.
	ErrFailedToFetch = errors.New("failed to fetch from URL")

	// ErrInvalidHTTPStatusCode is returned when an invalid HTTP status code is returned.
	ErrInvalidHTTPStatusCode = errors.New("invalid HTTP status code returned")

	// ErrIPv6AddressNotEnclosed is returned when an IPv6 address is not enclosed in brackets.
	ErrIPv6AddressNotEnclosed = errors.New("ipv6 address is not enclosed in brackets")

	// ErrInvalidIPv6Address is returned when the IPv6 address is invalid.
	ErrInvalidIPv6Address = errors.New("invalid ipv6 address")

	// ErrUnsupportedTypeForRat is returned when the type is unsupported for conversion to *big.Rat.
	ErrUnsupportedTypeForRat = errors.New("unsupported type for conversion to *big.Rat")

	// ErrFailedToConvertToRat is returned when a string fails to convert to *big.Rat.
	ErrFailedToConvertToRat = errors.New("failed to convert string to *big.Rat")

	// ErrFailedToResolveGlobalReference is returned when a global reference cannot be resolved.
	ErrFailedToResolveGlobalReference = errors.New("failed to resolve global reference")

	// ErrFailedToDecodeSegmentWithJSONPointer is returned when a segment cannot be decoded.
	ErrFailedToDecodeSegmentWithJSONPointer = errors.New("failed to decode segment")

	// ErrSegmentNotFoundForJSONPointer is returned when a segment is not found in the schema context.
	ErrSegmentNotFoundForJSONPointer = errors.New("segment not found in the schema context")

	// ErrFailedToResolveReference is returned when a reference cannot be resolved.
	ErrFailedToResolveReference = errors.New("failed to resolve reference")

	// ErrFailedToResolveDefinitions is returned when definitions in $defs cannot be resolved.
	ErrFailedToResolveDefinitions = errors.New("failed to resolve definitions in $defs")

	// ErrFailedToResolveItems is returned when items in an array schema cannot be resolved.
	ErrFailedToResolveItems = errors.New("failed to resolve items")

	// ErrInvalidJSONSchemaType is returned when the JSON schema type is invalid.
	ErrInvalidJSONSchemaType = errors.New("invalid JSON schema type")

	// ErrNilConstValue is returned when trying to unmarshal into a nil ConstValue.
	ErrNilConstValue = errors.New("cannot unmarshal into nil ConstValue")
)
View Source
var (
	ErrTypeConversion     = errors.New("type conversion failed")
	ErrTimeParseFailure   = errors.New("failed to parse time string")
	ErrTimeTypeConversion = errors.New("cannot convert to time.Time")
	ErrNilDestination     = errors.New("destination cannot be nil")
	ErrNotPointer         = errors.New("destination must be a pointer")
	ErrNilPointer         = errors.New("destination pointer cannot be nil")
)

Static errors for better error handling

View Source
var Formats = map[string]func(interface{}) bool{
	"date-time":             IsDateTime,
	"date":                  IsDate,
	"time":                  IsTime,
	"duration":              IsDuration,
	"period":                IsPeriod,
	"hostname":              IsHostname,
	"email":                 IsEmail,
	"ip-address":            IsIPV4,
	"ipv4":                  IsIPV4,
	"ipv6":                  IsIPV6,
	"uri":                   IsURI,
	"iri":                   IsURI,
	"uri-reference":         IsURIReference,
	"uriref":                IsURIReference,
	"iri-reference":         IsURIReference,
	"uri-template":          IsURITemplate,
	"json-pointer":          IsJSONPointer,
	"relative-json-pointer": IsRelativeJSONPointer,
	"uuid":                  IsUUID,
	"regex":                 IsRegex,
	"unknown":               func(interface{}) bool { return true },
}

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.

Functions ΒΆ

func FormatRat ΒΆ

func FormatRat(r *Rat) string

FormatRat formats a Rat as a string.

func GetI18n ΒΆ

func GetI18n() (*i18n.I18n, error)

func IsDate ΒΆ

func IsDate(v interface{}) bool

IsDate tells whether given string is a valid full-date production as defined by RFC 3339, section 5.6.

see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details

func IsDateTime ΒΆ

func IsDateTime(v interface{}) bool

IsDateTime tells whether given string is a valid date representation as defined by RFC 3339, section 5.6.

see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details

func IsDuration ΒΆ

func IsDuration(v interface{}) bool

IsDuration tells whether given string is a valid duration format from the ISO 8601 ABNF as given in Appendix A of RFC 3339.

see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A, for details

func IsEmail ΒΆ

func IsEmail(v interface{}) bool

IsEmail tells whether given string is a valid Internet email address as defined by RFC 5322, section 3.4.1.

See https://en.wikipedia.org/wiki/Email_address, for details.

func IsHostname ΒΆ

func IsHostname(v interface{}) bool

IsHostname tells whether given string is a valid representation for an Internet host name, as defined by RFC 1034 section 3.1 and RFC 1123 section 2.1.

See https://en.wikipedia.org/wiki/Hostname#Restrictions_on_valid_host_names, for details.

func IsIPV4 ΒΆ

func IsIPV4(v interface{}) bool

IsIPV4 tells whether given string is a valid representation of an IPv4 address according to the "dotted-quad" ABNF syntax as defined in RFC 2673, section 3.2.

func IsIPV6 ΒΆ

func IsIPV6(v interface{}) bool

IsIPV6 tells whether given string is a valid representation of an IPv6 address as defined in RFC 2373, section 2.2.

func IsJSONPointer ΒΆ

func IsJSONPointer(v interface{}) bool

IsJSONPointer tells whether given string is a valid JSON Pointer.

Note: It returns false for JSON Pointer URI fragments.

func IsPeriod ΒΆ

func IsPeriod(v interface{}) bool

IsPeriod tells whether given string is a valid period format from the ISO 8601 ABNF as given in Appendix A of RFC 3339.

see https://datatracker.ietf.org/doc/html/rfc3339#appendix-A, for details

func IsRegex ΒΆ

func IsRegex(v interface{}) bool

IsRegex tells whether given string is a valid regex pattern

func IsRelativeJSONPointer ΒΆ

func IsRelativeJSONPointer(v interface{}) bool

IsRelativeJSONPointer tells whether given string is a valid Relative JSON Pointer.

see https://tools.ietf.org/html/draft-handrews-relative-json-pointer-01#section-3

func IsTime ΒΆ

func IsTime(v interface{}) bool

IsTime tells whether given string is a valid full-time production as defined by RFC 3339, section 5.6.

see https://datatracker.ietf.org/doc/html/rfc3339#section-5.6, for details

func IsURI ΒΆ

func IsURI(v interface{}) bool

IsURI tells whether given string is valid URI, according to RFC 3986.

func IsURIReference ΒΆ

func IsURIReference(v interface{}) bool

IsURIReference tells whether given string is a valid URI Reference (either a URI or a relative-reference), according to RFC 3986.

func IsURITemplate ΒΆ

func IsURITemplate(v interface{}) bool

IsURITemplate tells whether given string is a valid URI Template according to RFC6570.

Current implementation does minimal validation.

func IsUUID ΒΆ

func IsUUID(v interface{}) bool

IsUUID tells whether given string is a valid uuid format as specified in RFC4122.

see https://datatracker.ietf.org/doc/html/rfc4122#page-4, for details

Types ΒΆ

type Compiler ΒΆ

type Compiler struct {
	Decoders       map[string]func(string) ([]byte, error)            // Decoders for various encoding formats.
	MediaTypes     map[string]func([]byte) (interface{}, error)       // Media type handlers for unmarshalling data.
	Loaders        map[string]func(url string) (io.ReadCloser, error) // Functions to load schemas from URLs.
	DefaultBaseURI string                                             // Base URI used to resolve relative references.
	AssertFormat   bool                                               // Flag to enforce format validation.
	// contains filtered or unexported fields
}

Compiler represents a JSON Schema compiler that manages schema compilation and caching.

func NewCompiler ΒΆ

func NewCompiler() *Compiler

NewCompiler creates a new Compiler instance and initializes it with default settings.

func (*Compiler) Compile ΒΆ

func (c *Compiler) Compile(jsonSchema []byte, uris ...string) (*Schema, error)

Compile compiles a JSON schema and caches it. If an URI is provided, it uses that as the key; otherwise, it generates a hash.

func (*Compiler) GetSchema ΒΆ

func (c *Compiler) GetSchema(ref string) (*Schema, error)

GetSchema retrieves a schema by reference. If the schema is not found in the cache and the ref is a URL, it tries to resolve it.

func (*Compiler) RegisterDecoder ΒΆ

func (c *Compiler) RegisterDecoder(encodingName string, decoderFunc func(string) ([]byte, error)) *Compiler

RegisterDecoder adds a new decoder function for a specific encoding.

func (*Compiler) RegisterLoader ΒΆ

func (c *Compiler) RegisterLoader(scheme string, loaderFunc func(url string) (io.ReadCloser, error)) *Compiler

RegisterLoader adds a new loader function for a specific URI scheme.

func (*Compiler) RegisterMediaType ΒΆ

func (c *Compiler) RegisterMediaType(mediaTypeName string, unmarshalFunc func([]byte) (interface{}, error)) *Compiler

RegisterMediaType adds a new unmarshal function for a specific media type.

func (*Compiler) SetAssertFormat ΒΆ

func (c *Compiler) SetAssertFormat(assert bool) *Compiler

SetAssertFormat enables or disables format assertion.

func (*Compiler) SetDefaultBaseURI ΒΆ

func (c *Compiler) SetDefaultBaseURI(baseURI string) *Compiler

SetDefaultBaseURI sets the default base URL for resolving relative references.

func (*Compiler) SetSchema ΒΆ

func (c *Compiler) SetSchema(uri string, schema *Schema) *Compiler

SetSchema associates a specific schema with a URI.

func (*Compiler) WithDecoderJSON ΒΆ added in v0.2.3

func (c *Compiler) WithDecoderJSON(decoder func(data []byte, v interface{}) error) *Compiler

WithDecoderJSON configures custom JSON decoder implementation

func (*Compiler) WithEncoderJSON ΒΆ added in v0.2.3

func (c *Compiler) WithEncoderJSON(encoder func(v interface{}) ([]byte, error)) *Compiler

WithEncoderJSON configures custom JSON encoder implementation

type ConstValue ΒΆ

type ConstValue struct {
	Value interface{}
	IsSet bool
}

ConstValue represents a constant value in a JSON Schema.

func (ConstValue) MarshalJSON ΒΆ

func (cv ConstValue) MarshalJSON() ([]byte, error)

MarshalJSON handles marshaling the ConstValue type back to JSON.

func (*ConstValue) UnmarshalJSON ΒΆ

func (cv *ConstValue) UnmarshalJSON(data []byte) error

UnmarshalJSON handles unmarshaling a JSON value into the ConstValue type.

type DynamicScope ΒΆ

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

DynamicScope struct defines a stack specifically for handling Schema types

func NewDynamicScope ΒΆ

func NewDynamicScope() *DynamicScope

NewDynamicScope creates and returns a new empty DynamicScope

func (*DynamicScope) IsEmpty ΒΆ

func (ds *DynamicScope) IsEmpty() bool

IsEmpty checks if the dynamic scope is empty

func (*DynamicScope) LookupDynamicAnchor ΒΆ

func (ds *DynamicScope) LookupDynamicAnchor(anchor string) *Schema

LookupDynamicAnchor searches for a dynamic anchor in the dynamic scope

func (*DynamicScope) Peek ΒΆ

func (ds *DynamicScope) Peek() *Schema

Peek returns the top Schema without removing it

func (*DynamicScope) Pop ΒΆ

func (ds *DynamicScope) Pop() *Schema

Pop removes and returns the top Schema from the dynamic scope

func (*DynamicScope) Push ΒΆ

func (ds *DynamicScope) Push(schema *Schema)

Push adds a Schema to the dynamic scope

func (*DynamicScope) Size ΒΆ

func (ds *DynamicScope) Size() int

Size returns the number of Schemas in the dynamic scope

type EvaluationError ΒΆ

type EvaluationError struct {
	Keyword string                 `json:"keyword"`
	Code    string                 `json:"code"`
	Message string                 `json:"message"`
	Params  map[string]interface{} `json:"params"`
}

func NewEvaluationError ΒΆ

func NewEvaluationError(keyword string, code string, message string, params ...map[string]interface{}) *EvaluationError

func (*EvaluationError) Error ΒΆ

func (e *EvaluationError) Error() string

func (*EvaluationError) Localize ΒΆ

func (e *EvaluationError) Localize(localizer *i18n.Localizer) string

type EvaluationResult ΒΆ

type EvaluationResult struct {
	Valid            bool                        `json:"valid"`
	EvaluationPath   string                      `json:"evaluationPath"`
	SchemaLocation   string                      `json:"schemaLocation"`
	InstanceLocation string                      `json:"instanceLocation"`
	Annotations      map[string]interface{}      `json:"annotations,omitempty"`
	Errors           map[string]*EvaluationError `json:"errors,omitempty"` // Store error messages here
	Details          []*EvaluationResult         `json:"details,omitempty"`
	// contains filtered or unexported fields
}

func NewEvaluationResult ΒΆ

func NewEvaluationResult(schema *Schema) *EvaluationResult

func (*EvaluationResult) AddAnnotation ΒΆ

func (e *EvaluationResult) AddAnnotation(keyword string, annotation interface{}) *EvaluationResult

func (*EvaluationResult) AddDetail ΒΆ

func (e *EvaluationResult) AddDetail(detail *EvaluationResult) *EvaluationResult

func (*EvaluationResult) AddError ΒΆ

func (*EvaluationResult) CollectAnnotations ΒΆ

func (e *EvaluationResult) CollectAnnotations() *EvaluationResult

func (*EvaluationResult) Error ΒΆ added in v0.2.2

func (e *EvaluationResult) Error() string

func (*EvaluationResult) IsValid ΒΆ

func (e *EvaluationResult) IsValid() bool

func (*EvaluationResult) SetEvaluationPath ΒΆ

func (e *EvaluationResult) SetEvaluationPath(evaluationPath string) *EvaluationResult

func (*EvaluationResult) SetInstanceLocation ΒΆ

func (e *EvaluationResult) SetInstanceLocation(instanceLocation string) *EvaluationResult

func (*EvaluationResult) SetInvalid ΒΆ

func (e *EvaluationResult) SetInvalid() *EvaluationResult

func (*EvaluationResult) SetSchemaLocation ΒΆ

func (e *EvaluationResult) SetSchemaLocation(location string) *EvaluationResult

func (*EvaluationResult) ToFlag ΒΆ

func (e *EvaluationResult) ToFlag() *Flag

Converts EvaluationResult to a simple Flag struct

func (*EvaluationResult) ToList ΒΆ

func (e *EvaluationResult) ToList(includeHierarchy ...bool) *List

ToList converts the evaluation results into a list format with optional hierarchy includeHierarchy is variadic; if not provided, it defaults to true

func (*EvaluationResult) ToLocalizeList ΒΆ

func (e *EvaluationResult) ToLocalizeList(localizer *i18n.Localizer, includeHierarchy ...bool) *List

ToLocalizeList converts the evaluation results into a list format with optional hierarchy with localization includeHierarchy is variadic; if not provided, it defaults to true

type FieldCache ΒΆ added in v0.2.5

type FieldCache struct {
	FieldsByName map[string]FieldInfo
	FieldCount   int
}

FieldCache stores parsed field information for a struct type

type FieldInfo ΒΆ added in v0.2.5

type FieldInfo struct {
	Index     int          // Field index in the struct
	JSONName  string       // JSON field name (after processing tags)
	Omitempty bool         // Whether the field has omitempty tag
	Type      reflect.Type // Field type
}

FieldInfo contains metadata for a struct field

type Flag ΒΆ

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

type List ΒΆ

type List struct {
	Valid            bool                   `json:"valid"`
	EvaluationPath   string                 `json:"evaluationPath"`
	SchemaLocation   string                 `json:"schemaLocation"`
	InstanceLocation string                 `json:"instanceLocation"`
	Annotations      map[string]interface{} `json:"annotations,omitempty"`
	Errors           map[string]string      `json:"errors,omitempty"`
	Details          []List                 `json:"details,omitempty"`
}

type Rat ΒΆ

type Rat struct {
	*big.Rat
}

Rat wraps a big.Rat to enable custom JSON marshaling and unmarshaling.

func NewRat ΒΆ

func NewRat(value interface{}) *Rat

NewRat creates a new Rat instance from a given value.

func (*Rat) MarshalJSON ΒΆ

func (r *Rat) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for Rat.

func (*Rat) UnmarshalJSON ΒΆ

func (r *Rat) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for Rat.

type Schema ΒΆ

type Schema struct {
	ID     string  `json:"$id,omitempty"`     // Public identifier for the schema.
	Schema string  `json:"$schema,omitempty"` // URI indicating the specification the schema conforms to.
	Format *string `json:"format,omitempty"`  // Format hint for string data, e.g., "email" or "date-time".

	// Schema reference keywords, see https://json-schema.org/draft/2020-12/json-schema-core#ref
	Ref                string             `json:"$ref,omitempty"`           // Reference to another schema.
	DynamicRef         string             `json:"$dynamicRef,omitempty"`    // Reference to another schema that can be dynamically resolved.
	Anchor             string             `json:"$anchor,omitempty"`        // Anchor for resolving relative JSON Pointers.
	DynamicAnchor      string             `json:"$dynamicAnchor,omitempty"` // Anchor for dynamic resolution
	Defs               map[string]*Schema `json:"$defs,omitempty"`          // An object containing schema definitions.
	ResolvedRef        *Schema            `json:"-"`                        // Resolved schema for $ref
	ResolvedDynamicRef *Schema            `json:"-"`                        // Resolved schema for $dynamicRef

	// Boolean JSON Schemas, see https://json-schema.org/draft/2020-12/json-schema-core#name-boolean-json-schemas
	Boolean *bool `json:"-"` // Boolean schema, used for quick validation.

	// Applying subschemas with logical keywords, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subsch
	AllOf []*Schema `json:"allOf,omitempty"` // Array of schemas for validating the instance against all of them.
	AnyOf []*Schema `json:"anyOf,omitempty"` // Array of schemas for validating the instance against any of them.
	OneOf []*Schema `json:"oneOf,omitempty"` // Array of schemas for validating the instance against exactly one of them.
	Not   *Schema   `json:"not,omitempty"`   // Schema for validating the instance against the negation of it.

	// Applying subschemas conditionally, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subsche
	If               *Schema            `json:"if,omitempty"`               // Schema to be evaluated as a condition
	Then             *Schema            `json:"then,omitempty"`             // Schema to be evaluated if 'if' is successful
	Else             *Schema            `json:"else,omitempty"`             // Schema to be evaluated if 'if' is not successful
	DependentSchemas map[string]*Schema `json:"dependentSchemas,omitempty"` // Dependent schemas based on property presence

	// Applying subschemas to array keywords, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subschem
	PrefixItems []*Schema `json:"prefixItems,omitempty"` // Array of schemas for validating the array items' prefix.
	Items       *Schema   `json:"items,omitempty"`       // Schema for items in an array.
	Contains    *Schema   `json:"contains,omitempty"`    // Schema for validating items in the array.

	// Applying subschemas to objects keywords, see https://json-schema.org/draft/2020-12/json-schema-core#name-keywords-for-applying-subschemas
	Properties           *SchemaMap `json:"properties,omitempty"`           // Definitions of properties for object types.
	PatternProperties    *SchemaMap `json:"patternProperties,omitempty"`    // Definitions of properties for object types matched by specific patterns.
	AdditionalProperties *Schema    `json:"additionalProperties,omitempty"` // Can be a boolean or a schema, controls additional properties handling.
	PropertyNames        *Schema    `json:"propertyNames,omitempty"`        // Can be a boolean or a schema, controls property names validation.

	// Any validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.1
	Type  SchemaType    `json:"type,omitempty"`  // Can be a single type or an array of types.
	Enum  []interface{} `json:"enum,omitempty"`  // Enumerated values for the property.
	Const *ConstValue   `json:"const,omitempty"` // Constant value for the property.

	// Numeric validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.2
	MultipleOf       *Rat `json:"multipleOf,omitempty"`       // Number must be a multiple of this value, strictly greater than 0.
	Maximum          *Rat `json:"maximum,omitempty"`          // Maximum value of the number.
	ExclusiveMaximum *Rat `json:"exclusiveMaximum,omitempty"` // Number must be less than this value.
	Minimum          *Rat `json:"minimum,omitempty"`          // Minimum value of the number.
	ExclusiveMinimum *Rat `json:"exclusiveMinimum,omitempty"` // Number must be greater than this value.

	// String validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.3
	MaxLength *float64 `json:"maxLength,omitempty"` // Maximum length of a string.
	MinLength *float64 `json:"minLength,omitempty"` // Minimum length of a string.
	Pattern   *string  `json:"pattern,omitempty"`   // Regular expression pattern to match the string against.

	// Array validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.4
	MaxItems    *float64 `json:"maxItems,omitempty"`    // Maximum number of items in an array.
	MinItems    *float64 `json:"minItems,omitempty"`    // Minimum number of items in an array.
	UniqueItems *bool    `json:"uniqueItems,omitempty"` // Whether the items in the array must be unique.
	MaxContains *float64 `json:"maxContains,omitempty"` // Maximum number of items in the array that can match the contains schema.
	MinContains *float64 `json:"minContains,omitempty"` // Minimum number of items in the array that must match the contains schema.

	// https://json-schema.org/draft/2020-12/json-schema-core#name-unevaluateditems
	UnevaluatedItems *Schema `json:"unevaluatedItems,omitempty"` // Schema for unevaluated items in an array.

	// Object validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#section-6.5
	MaxProperties     *float64            `json:"maxProperties,omitempty"`     // Maximum number of properties in an object.
	MinProperties     *float64            `json:"minProperties,omitempty"`     // Minimum number of properties in an object.
	Required          []string            `json:"required,omitempty"`          // List of required property names for object types.
	DependentRequired map[string][]string `json:"dependentRequired,omitempty"` // Properties required when another property is present.

	// https://json-schema.org/draft/2020-12/json-schema-core#name-unevaluatedproperties
	UnevaluatedProperties *Schema `json:"unevaluatedProperties,omitempty"` // Schema for unevaluated properties in an object.

	// Content validation keywords, see https://json-schema.org/draft/2020-12/json-schema-validation#name-a-vocabulary-for-the-conten
	ContentEncoding  *string `json:"contentEncoding,omitempty"`  // Encoding format of the content.
	ContentMediaType *string `json:"contentMediaType,omitempty"` // Media type of the content.
	ContentSchema    *Schema `json:"contentSchema,omitempty"`    // Schema for validating the content.

	// Meta-data for schema and instance description, see https://json-schema.org/draft/2020-12/json-schema-validation#name-a-vocabulary-for-basic-meta
	Title       *string       `json:"title,omitempty"`       // A short summary of the schema.
	Description *string       `json:"description,omitempty"` // A detailed description of the purpose of the schema.
	Default     interface{}   `json:"default,omitempty"`     // Default value of the instance.
	Deprecated  *bool         `json:"deprecated,omitempty"`  // Indicates that the schema is deprecated.
	ReadOnly    *bool         `json:"readOnly,omitempty"`    // Indicates that the property is read-only.
	WriteOnly   *bool         `json:"writeOnly,omitempty"`   // Indicates that the property is write-only.
	Examples    []interface{} `json:"examples,omitempty"`    // Examples of the instance data that validates against this schema.
	// contains filtered or unexported fields
}

Schema represents a JSON Schema as per the 2020-12 draft, containing all necessary metadata and validation properties defined by the specification.

func (*Schema) GetSchemaLocation ΒΆ

func (s *Schema) GetSchemaLocation(anchor string) string

func (*Schema) GetSchemaURI ΒΆ

func (s *Schema) GetSchemaURI() string

GetSchemaURI returns the resolved URI for the schema, or an empty string if no URI is defined.

func (*Schema) MarshalJSON ΒΆ

func (s *Schema) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler

func (*Schema) Unmarshal ΒΆ added in v0.2.6

func (s *Schema) Unmarshal(dst, src interface{}) error

Unmarshal unmarshals data into dst, applying default values from the schema. This method does NOT perform validation - use Validate() separately for validation.

Supported source types:

  • []byte (JSON data - automatically parsed if valid JSON)
  • map[string]interface{} (parsed JSON object)
  • Go structs and other types

Supported destination types:

  • *struct (Go struct pointer)
  • *map[string]interface{} (map pointer)
  • other pointer types (via JSON marshaling)

Example usage:

result := schema.Validate(data)
if result.IsValid() {
    err := schema.Unmarshal(&user, data)
    if err != nil {
        log.Fatal(err)
    }
} else {
    // Handle validation errors
    for field, err := range result.Errors {
        log.Printf("%s: %s", field, err.Message)
    }
}

To use JSON strings, convert them to []byte first:

schema.Unmarshal(&target, []byte(jsonString))

func (*Schema) UnmarshalJSON ΒΆ

func (s *Schema) UnmarshalJSON(data []byte) error

UnmarshalJSON handles unmarshaling JSON data into the Schema type.

func (*Schema) Validate ΒΆ

func (s *Schema) Validate(instance interface{}) *EvaluationResult

Validate checks if the given instance conforms to the schema. This method automatically detects the input type and delegates to the appropriate validation method.

func (*Schema) ValidateJSON ΒΆ added in v0.3.0

func (s *Schema) ValidateJSON(data []byte) *EvaluationResult

ValidateJSON validates JSON data provided as []byte. The input is guaranteed to be treated as JSON data and parsed accordingly.

func (*Schema) ValidateMap ΒΆ added in v0.3.0

func (s *Schema) ValidateMap(data map[string]interface{}) *EvaluationResult

ValidateMap validates map[string]interface{} data directly. This method provides optimal performance for pre-parsed JSON data.

func (*Schema) ValidateStruct ΒΆ added in v0.3.0

func (s *Schema) ValidateStruct(instance interface{}) *EvaluationResult

ValidateStruct validates Go struct data directly using reflection. This method uses cached reflection data for optimal performance.

type SchemaMap ΒΆ

type SchemaMap map[string]*Schema

SchemaMap represents a map of string keys to *Schema values, used primarily for properties and patternProperties.

func (SchemaMap) MarshalJSON ΒΆ

func (sm SchemaMap) MarshalJSON() ([]byte, error)

MarshalJSON ensures that SchemaMap serializes properly as a JSON object.

func (*SchemaMap) UnmarshalJSON ΒΆ

func (sm *SchemaMap) UnmarshalJSON(data []byte) error

UnmarshalJSON ensures that JSON objects are correctly parsed into SchemaMap, supporting the detailed structure required for nested schema definitions.

type SchemaType ΒΆ added in v0.2.0

type SchemaType []string

SchemaType holds a set of SchemaType values, accommodating complex schema definitions that permit multiple types.

func (SchemaType) MarshalJSON ΒΆ added in v0.2.0

func (r SchemaType) MarshalJSON() ([]byte, error)

MarshalJSON customizes the JSON serialization of SchemaType.

func (*SchemaType) UnmarshalJSON ΒΆ added in v0.2.0

func (r *SchemaType) UnmarshalJSON(data []byte) error

UnmarshalJSON customizes the JSON deserialization into SchemaType.

type UnmarshalError ΒΆ added in v0.2.6

type UnmarshalError struct {
	Type   string
	Field  string
	Reason string
	Err    error
}

UnmarshalError represents an error that occurred during unmarshaling

func (*UnmarshalError) Error ΒΆ added in v0.2.6

func (e *UnmarshalError) Error() string

func (*UnmarshalError) Unwrap ΒΆ added in v0.2.6

func (e *UnmarshalError) Unwrap() error

Directories ΒΆ

Path Synopsis
examples
basic command
error-handling command
i18n command
unmarshaling command

Jump to

Keyboard shortcuts

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