jsonschema

package module
v0.2.6 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 ยถ

JsonSchema Validator for Go

Go Version License Test Status

๐Ÿš€ A high-performance, feature-rich JSON Schema validator for Go that supports JSON Schema Draft 2020-12 with direct struct validation, intelligent byte array handling, and smart unmarshaling with automatic default value application.

Table of Contents

๐ŸŒŸ Key Features

  • โœ… JSON Schema Draft 2020-12 - Full compliance with the latest specification
  • ๐Ÿš€ Direct Struct Validation - Zero-allocation validation of Go structs without map conversion
  • ๐Ÿ”„ Smart Unmarshal - Validation + unmarshaling + automatic default value application in one step
  • ๐Ÿงช Test Suite Verified - Passes all JSON Schema Test Suite cases (except vocabulary)
  • ๐ŸŒ Internationalization - Support for 9 languages with localized error messages
  • ๐Ÿ“Š Enhanced Output - Detailed validation results with multiple output formats
  • โšก High Performance - Configurable JSON encoder/decoder with caching optimizations
  • ๐Ÿ”— Remote Schema Loading - Load schemas from URLs with automatic caching
  • ๐Ÿ›ก๏ธ Type Safety - Full support for Go's type system including pointers, time.Time, and nested structs

๐Ÿ“ฆ Installation

go get github.com/kaptinlin/jsonschema

Requirements: Go 1.21.1 or higher

โšก Quick Start

package main

import (
    "fmt"
    "log"
    "github.com/kaptinlin/jsonschema"
)

func main() {
    // 1. Define your JSON schema
    schemaJSON := `{
        "type": "object",
        "properties": {
            "name": {"type": "string", "minLength": 1},
            "age": {"type": "integer", "minimum": 0, "maximum": 120},
            "email": {"type": "string", "format": "email"}
        },
        "required": ["name", "age"]
    }`

    // 2. Compile the schema
    compiler := jsonschema.NewCompiler()
    schema, err := compiler.Compile([]byte(schemaJSON))
    if err != nil {
        log.Fatal("Schema compilation failed:", err)
    }

    // 3. Validate your data
    person := map[string]interface{}{
        "name": "Alice",
        "age":  30,
        "email": "alice@example.com",
    }
    
    result := schema.Validate(person)
    if result.IsValid() {
        fmt.Println("โœ… Validation passed!")
    } else {
        fmt.Printf("โŒ Validation failed: %v\n", result.Errors)
    }
}

๐Ÿ“ Validation

Input Types Support

The validator handles various input types with clear, predictable behavior:

// 1. JSON bytes ([]byte) - automatically parsed as JSON if valid
jsonBytes := []byte(`{"name": "John", "age": 25}`)
result := schema.Validate(jsonBytes)

// 2. Go structs (zero-allocation validation)
type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}
person := Person{Name: "Bob", Age: 35}
result = schema.Validate(person)

// 3. Maps and interfaces
data := map[string]interface{}{"name": "Alice", "age": 28}
result = schema.Validate(data)

// 4. Raw bytes (treated as byte array, not parsed as JSON)
rawBytes := []byte{1, 2, 3}
result = schema.Validate(rawBytes) // Validates as array of integers

// 5. JSON strings 
jsonString := `{"name": "Jane", "age": 30}`
result = schema.Validate([]byte(jsonString))
Smart Byte Array Handling

The validator intelligently handles []byte input:

  • Valid JSON: Automatically parsed and validated as JSON objects/arrays
  • Invalid JSON-like: Returns validation error for malformed JSON (starts with { or [)
  • Binary Data: Treated as regular byte array for validation
// These bytes will be parsed as JSON object
jsonBytes := []byte(`{"name": "John", "age": 25}`)

// These bytes will be treated as byte array
binaryBytes := []byte{0x48, 0x65, 0x6c, 0x6c, 0x6f} // "Hello" in bytes

// This will return a JSON parsing error
malformedJSON := []byte(`{"name": "John", "age":`)
Validation Results
result := schema.Validate(data)

// Check if valid
if result.IsValid() {
    fmt.Println("Data is valid!")
}

// Get detailed errors
errors := result.Errors
for field, err := range errors {
    fmt.Printf("Field '%s': %v\n", field, err)
}

// Different output formats
flag := result.ToFlag()                    // Simple boolean
list := result.ToList()                    // Detailed list
hierarchical := result.ToList(false)       // Hierarchical structure

๐Ÿ”„ Unmarshal with Defaults

The Unmarshal method combines validation, unmarshaling, and automatic default value application in a single operation. It follows the same input pattern as json.Unmarshal for consistency.

// Define schema with default values
schemaJSON := `{
    "type": "object",
    "properties": {
        "name": {"type": "string"},
        "age": {"type": "integer", "minimum": 0},
        "country": {"type": "string", "default": "US"},
        "active": {"type": "boolean", "default": true},
        "role": {"type": "string", "default": "user"}
    },
    "required": ["name", "age"]
}`

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

type User struct {
    Name    string `json:"name"`
    Age     int    `json:"age"`
    Country string `json:"country"`
    Active  bool   `json:"active"`
    Role    string `json:"role"`
}

// 1. Unmarshal from JSON bytes (like json.Unmarshal)
jsonData := []byte(`{"name": "John", "age": 25}`)
var user1 User
err := schema.Unmarshal(&user1, jsonData)
// Result: User{Name: "John", Age: 25, Country: "US", Active: true, Role: "user"}

// 2. Unmarshal from JSON string (convert to []byte first)
jsonString := `{"name": "Jane", "age": 30, "country": "CA"}`
var user2 User
err = schema.Unmarshal(&user2, []byte(jsonString))
// Result: User{Name: "Jane", Age: 30, Country: "CA", Active: true, Role: "user"}

// 3. Unmarshal from map
data := map[string]interface{}{"name": "Bob", "age": 35}
var user3 User
err = schema.Unmarshal(&user3, data)
// Result: User{Name: "Bob", Age: 35, Country: "US", Active: true, Role: "user"}
Input Types
Type Usage Example
[]byte JSON data (like json.Unmarshal) []byte({"name": "John"})
map[string]interface{} Parsed JSON object map[string]interface{}{"name": "John"}
Go structs Direct struct validation User{Name: "John", Age: 25}
Output Types
Type Description
*struct Unmarshal to Go struct with JSON tags
*map[string]interface{} Unmarshal to generic map
Other pointer types Via JSON round-trip conversion

๐Ÿ—๏ธ Struct Validation

Validate Go structs directly without JSON serialization overhead:

type Address struct {
    Street  string `json:"street"`
    City    string `json:"city"`
    Country string `json:"country"`
}

type User struct {
    ID       int        `json:"id"`
    Name     string     `json:"name"`
    Email    *string    `json:"email,omitempty"`     // Optional pointer field
    Age      int        `json:"age"`
    Address  *Address   `json:"address,omitempty"`   // Nested optional struct
    Tags     []string   `json:"tags"`                // Array field
    Created  time.Time  `json:"created_at"`          // Time field (auto-formatted)
    Metadata map[string]interface{} `json:"metadata"` // Dynamic fields
}

user := User{
    ID:   1,
    Name: "John Doe",
    Age:  30,
    Tags: []string{"admin", "user"},
    Created: time.Now(),
}

result := schema.Validate(user)
Struct Validation Features
  • ๐Ÿท๏ธ JSON Tag Support - Full support for json:"-", omitempty, custom names
  • ๐Ÿ—๏ธ Nested Structures - Deep validation of complex object hierarchies
  • ๐Ÿ“ Pointer Fields - Proper handling of pointer types and nil values
  • โฐ Time Support - Automatic RFC3339 formatting for time.Time fields
  • ๐Ÿ“Š Array/Slice Support - Validation of arrays and slices with item schemas
  • ๐Ÿ—บ๏ธ Map Support - Dynamic key-value validation
  • โšก Performance - Field caching and zero-allocation validation paths
  • ๐Ÿ”„ Interface Support - Handles interface{} types intelligently

โš™๏ธ Advanced Usage

Schema Compilation Options
compiler := jsonschema.NewCompiler()

// Set default base URI for resolving relative references
compiler.SetDefaultBaseURI("https://example.com/schemas/")

// Enable format assertions (email, date-time, etc.)
compiler.SetAssertFormat(true)

// Register custom format validator
compiler.RegisterFormat("custom-id", func(value string) bool {
    return len(value) == 10 // Example validation
})
Custom JSON Encoder/Decoder
import "github.com/bytedance/sonic" // High-performance JSON library

compiler := jsonschema.NewCompiler()
compiler.WithEncoderJSON(sonic.Marshal)
compiler.WithDecoderJSON(sonic.Unmarshal)
Remote Schema Loading
// Load schema from URL
schema, err := compiler.GetSchema("https://json-schema.org/draft/2020-12/schema")

// Register custom loaders
compiler.RegisterLoader("file", func(uri string) ([]byte, error) {
    return os.ReadFile(strings.TrimPrefix(uri, "file://"))
})
Error Output Formats
result := schema.Validate(data)

// Basic errors map
errors := result.Errors

// Detailed list with paths
details := result.ToList()

// Hierarchical structure (preserves nesting)
hierarchical := result.ToList(false)

// Simple boolean for quick checks
isValid := result.ToFlag()
Internationalization
// Get i18n support
i18n, err := jsonschema.GetI18n()
if err != nil {
    log.Fatal(err)
}

// Create localizer for specific language
localizer := i18n.NewLocalizer("zh-Hans") // Simplified Chinese

// Validate and get localized errors
result := schema.Validate(data)
localizedErrors := result.ToLocalizeList(localizer)

for _, error := range localizedErrors {
    fmt.Printf("้”™่ฏฏ: %s\n", error.Message)
}

๐Ÿ“š Examples

Explore comprehensive examples in the examples/ directory:

๐Ÿค Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

Development Setup
# Clone repository with test suite submodule
git clone --recurse-submodules https://github.com/kaptinlin/jsonschema.git

# Install dependencies
go mod download

# Run tests
go test -v ./...

# Run official JSON Schema test suite
cd tests && go test -v
Project Structure
โ”œโ”€โ”€ compiler.go          # Schema compilation and caching
โ”œโ”€โ”€ validate.go          # Core validation logic
โ”œโ”€โ”€ unmarshal.go         # Unmarshal with defaults
โ”œโ”€โ”€ struct_validation.go # Direct struct validation
โ”œโ”€โ”€ formats.go          # Format validators
โ”œโ”€โ”€ i18n/               # Internationalization files
โ”œโ”€โ”€ examples/           # Example applications
โ””โ”€โ”€ tests/             # Official test suite

๐Ÿ“„ License

This project is licensed under the MIT License - see the 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")
)

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 validates the source data against the schema and unmarshals it into dst, applying default values for missing fields as defined in the schema.

This method follows the same input pattern as json.Unmarshal - only accepting []byte for JSON data.

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)

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

Evaluate checks if the given instance conforms to the schema.

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
advanced-struct command
basic command
i18n command
jsonschema command

Jump to

Keyboard shortcuts

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