jsonschema

package module
v0.4.6 Latest Latest
Warning

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

Go to latest
Published: Jul 1, 2025 License: MIT Imports: 25 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
  • Code Construction - Type-safe schema building using JSON Schema keywords

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
}
Dynamic Default Values

Register functions to generate dynamic defaults during unmarshaling:

// Register custom functions
compiler := jsonschema.NewCompiler()
compiler.RegisterDefaultFunc("now", jsonschema.DefaultNowFunc)
compiler.RegisterDefaultFunc("uuid", func(args ...any) (any, error) {
    return uuid.New().String(), nil
})

// Schema with dynamic defaults
schemaJSON := `{
    "type": "object",
    "properties": {
        "id": {"default": "uuid()"},
        "createdAt": {"default": "now()"},
        "formattedDate": {"default": "now(2006-01-02)"},
        "status": {"default": "active"}
    }
}`

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

// Input: {}  
// Result: {
//   "id": "3ace637a-515a-4328-a614-b3deb58d410d",
//   "createdAt": "2025-06-05T01:05:22+08:00",
//   "formattedDate": "2025-06-05",
//   "status": "active"
// }

Programmatic Schema Building

Create JSON schemas directly in Go code with type-safe constructors:

// Define schemas with fluent API
schema := jsonschema.Object(
    jsonschema.Prop("name", jsonschema.String(jsonschema.MinLen(1))),
    jsonschema.Prop("email", jsonschema.Email()),
    jsonschema.Required("name", "email"),
)

// Validate immediately - no compilation step
result := schema.Validate(data)
Key Features
  • Core Types: String, Integer, Array, Object with validation keywords
  • Composition: OneOf, AnyOf, AllOf, conditional logic (If/Then/Else)
  • Formats: Built-in validators for email, UUID, datetime, URI, etc.
  • Registration: Register schemas for reuse and cross-references

📖 Full Documentation: docs/constructor.md

Custom Compiler for Schemas

Set custom compilers on schemas for isolated function registries:

// Create custom compiler with functions
compiler := jsonschema.NewCompiler()
compiler.RegisterDefaultFunc("now", jsonschema.DefaultNowFunc)

// Apply to programmatically built schema
schema := jsonschema.Object(
    jsonschema.Prop("timestamp", jsonschema.String(jsonschema.Default("now()"))),
    jsonschema.Prop("name", jsonschema.String()),
).SetCompiler(compiler)

// Child schemas automatically inherit parent's compiler
result := schema.Validate(data)

Advanced Features

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

// Use in schema
schema := `{
    "type": "string",
    "format": "uuid"
}`
Schema References
schema := `{
    "type": "object",
    "properties": {
        "user": {"$ref": "#/$defs/User"}
    },
    "$defs": {
        "User": {
            "type": "object",
            "properties": {
                "name": {"type": "string"}
            }
        }
    }
}`
Internationalization
// Set custom error messages
compiler.SetLocale("zh-CN")

// Or use custom translator
compiler.SetTranslator(func(key string, args ...interface{}) string {
    return customTranslate(key, args...)
})
Performance Optimization
// Pre-compile schemas for better performance
compiler := jsonschema.NewCompiler()
schema := compiler.MustCompile(schemaJSON)

// Use type-specific validation methods
result := schema.ValidateStruct(structData)  // Fastest for structs
result := schema.ValidateJSON(jsonBytes)     // Fastest for JSON
result := schema.ValidateMap(mapData)        // Fastest for maps

Error Handling

Detailed Error Information
result := schema.Validate(data)
if !result.IsValid() {
    // Get all errors
    for field, err := range result.Errors {
        fmt.Printf("Field: %s\n", field)
        fmt.Printf("Message: %s\n", err.Message)
        fmt.Printf("Value: %v\n", err.Value)
        fmt.Printf("Schema: %v\n", err.Schema)
    }
    
    // Or get as a list
    errors := result.ToList()
    for _, err := range errors {
        fmt.Printf("Error: %s\n", err.Error())
    }
}
Custom Error Messages
schema := `{
    "type": "string",
    "minLength": 5,
    "errorMessage": "Name must be at least 5 characters long"
}`

Testing

The library includes comprehensive tests and passes the official JSON Schema Test Suite:

go test ./...
Benchmarks
go test -bench=. -benchmem

Contributing

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

Development Setup
git clone https://github.com/kaptinlin/jsonschema.git
cd jsonschema
go mod download
go test ./...

License

This project is licensed under the MIT License - see the LICENSE file for details.

Acknowledgments

  • Thanks to the JSON Schema community for the excellent specification
  • Inspired by other JSON Schema implementations in various languages
  • Special thanks to all contributors who have helped improve this library

Documentation

Overview

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

Example (ArraySchema)
package main

import (
	"fmt"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// Array schema with validation keywords
	numbersSchema := jsonschema.Array(
		jsonschema.Items(jsonschema.Number(
			jsonschema.Min(0),
			jsonschema.Max(100),
		)),
		jsonschema.MinItems(1),
		jsonschema.MaxItems(10),
	)

	validData := []interface{}{10, 20, 30}
	result := numbersSchema.Validate(validData)
	fmt.Println("Numbers valid:", result.IsValid())

	invalidData := []interface{}{-5, 150} // Out of range
	result = numbersSchema.Validate(invalidData)
	fmt.Println("Invalid numbers valid:", result.IsValid())
}
Output:

Numbers valid: true
Invalid numbers valid: false
Example (CompatibilityWithJSON)
package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// New code construction approach
	codeSchema := jsonschema.Object(
		jsonschema.Prop("name", jsonschema.String()),
		jsonschema.Prop("age", jsonschema.Integer()),
	)

	// Existing JSON compilation approach
	compiler := jsonschema.NewCompiler()
	jsonSchema, err := compiler.Compile([]byte(`{
		"type": "object",
		"properties": {
			"name": {"type": "string"},
			"age": {"type": "integer"}
		}
	}`))
	if err != nil {
		log.Fatal(err)
	}

	data := map[string]interface{}{
		"name": "Bob",
		"age":  25,
	}

	// Both approaches work identically
	result1 := codeSchema.Validate(data)
	result2 := jsonSchema.Validate(data)

	fmt.Println("Code schema valid:", result1.IsValid())
	fmt.Println("JSON schema valid:", result2.IsValid())
}
Output:

Code schema valid: true
JSON schema valid: true
Example (ComplexSchema)
package main

import (
	"fmt"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// Complex nested schema with validation keywords
	userSchema := jsonschema.Object(
		jsonschema.Prop("name", jsonschema.String(
			jsonschema.MinLen(1),
			jsonschema.MaxLen(100),
		)),
		jsonschema.Prop("age", jsonschema.Integer(
			jsonschema.Min(0),
			jsonschema.Max(150),
		)),
		jsonschema.Prop("email", jsonschema.Email()),
		jsonschema.Prop("address", jsonschema.Object(
			jsonschema.Prop("street", jsonschema.String(jsonschema.MinLen(1))),
			jsonschema.Prop("city", jsonschema.String(jsonschema.MinLen(1))),
			jsonschema.Prop("zip", jsonschema.String(jsonschema.Pattern(`^\d{5}$`))),
			jsonschema.Required("street", "city"),
		)),
		jsonschema.Prop("tags", jsonschema.Array(
			jsonschema.Items(jsonschema.String()),
			jsonschema.MinItems(1),
			jsonschema.UniqueItems(true),
		)),
		jsonschema.Required("name", "email"),
	)

	// Test data
	userData := map[string]interface{}{
		"name":  "Alice",
		"age":   30,
		"email": "alice@example.com",
		"address": map[string]interface{}{
			"street": "123 Main St",
			"city":   "Anytown",
			"zip":    "12345",
		},
		"tags": []interface{}{"developer", "go"},
	}

	result := userSchema.Validate(userData)
	if result.IsValid() {
		fmt.Println("User data is valid")
	} else {
		for field, err := range result.Errors {
			fmt.Printf("Error in %s: %s\n", field, err.Message)
		}
	}
}
Output:

User data is valid
Example (ConditionalSchema)
package main

import (
	"fmt"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// Conditional schema using if/then/else keywords
	conditionalSchema := jsonschema.If(
		jsonschema.Object(
			jsonschema.Prop("type", jsonschema.Const("premium")),
		),
	).Then(
		jsonschema.Object(
			jsonschema.Prop("features", jsonschema.Array(jsonschema.MinItems(5))),
		),
	).Else(
		jsonschema.Object(
			jsonschema.Prop("features", jsonschema.Array(jsonschema.MaxItems(3))),
		),
	)

	// Basic plan object
	basicPlan := map[string]interface{}{
		"type":     "basic",
		"features": []interface{}{"feature1", "feature2"},
	}

	result := conditionalSchema.Validate(basicPlan)
	fmt.Println("Basic plan valid:", result.IsValid())
}
Output:

Basic plan valid: true
Example (ConvenienceFunctions)
package main

import (
	"fmt"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// Using convenience functions that apply format keywords
	profileSchema := jsonschema.Object(
		jsonschema.Prop("id", jsonschema.UUID()),
		jsonschema.Prop("email", jsonschema.Email()),
		jsonschema.Prop("website", jsonschema.URI()),
		jsonschema.Prop("created", jsonschema.DateTime()),
		jsonschema.Prop("score", jsonschema.PositiveInt()),
	)

	data := map[string]interface{}{
		"id":      "550e8400-e29b-41d4-a716-446655440000",
		"email":   "user@example.com",
		"website": "https://example.com",
		"created": "2023-01-01T00:00:00Z",
		"score":   95,
	}

	result := profileSchema.Validate(data)
	fmt.Println("Profile valid:", result.IsValid())
}
Output:

Profile valid: true
Example (EnumAndConst)
package main

import (
	"fmt"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// Enum schema using enum keyword
	statusSchema := jsonschema.Enum("active", "inactive", "pending")

	result := statusSchema.Validate("active")
	fmt.Println("Status valid:", result.IsValid())

	// Const schema using const keyword
	versionSchema := jsonschema.Const("1.0.0")

	result = versionSchema.Validate("1.0.0")
	fmt.Println("Version valid:", result.IsValid())
}
Output:

Status valid: true
Version valid: true
Example (Object)
package main

import (
	"fmt"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// Simple object schema using constructor API
	schema := jsonschema.Object(
		jsonschema.Prop("name", jsonschema.String(jsonschema.MinLen(1))),
		jsonschema.Prop("age", jsonschema.Integer(jsonschema.Min(0))),
		jsonschema.Required("name"),
	)

	// Valid data
	data := map[string]interface{}{
		"name": "Alice",
		"age":  30,
	}

	result := schema.Validate(data)
	fmt.Println("Valid:", result.IsValid())
}
Output:

Valid: true
Example (OneOfAnyOf)
package main

import (
	"fmt"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// OneOf: exactly one schema must match
	oneOfSchema := jsonschema.OneOf(
		jsonschema.String(),
		jsonschema.Integer(),
	)

	result := oneOfSchema.Validate("hello")
	fmt.Println("OneOf string valid:", result.IsValid())

	// AnyOf: at least one schema must match
	anyOfSchema := jsonschema.AnyOf(
		jsonschema.String(jsonschema.MinLen(5)),
		jsonschema.Integer(jsonschema.Min(0)),
	)

	result = anyOfSchema.Validate("hi") // Matches integer rule (length < 5 but is string)
	fmt.Println("AnyOf short string valid:", result.IsValid())
}
Output:

OneOf string valid: true
AnyOf short string valid: false
Example (SchemaRegistration)
package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonschema"
)

func main() {
	// Create compiler for schema registration
	compiler := jsonschema.NewCompiler()

	// Create User schema with Constructor API
	userSchema := jsonschema.Object(
		jsonschema.ID("https://example.com/schemas/user"),
		jsonschema.Prop("id", jsonschema.UUID()),
		jsonschema.Prop("name", jsonschema.String(jsonschema.MinLen(1))),
		jsonschema.Prop("email", jsonschema.Email()),
		jsonschema.Required("id", "name", "email"),
	)

	// Register the schema
	compiler.SetSchema("https://example.com/schemas/user", userSchema)

	// Create Profile schema that references User schema
	profileJSON := `{
		"type": "object",
		"properties": {
			"user": {"$ref": "https://example.com/schemas/user"},
			"bio": {"type": "string"},
			"website": {"type": "string", "format": "uri"}
		},
		"required": ["user"]
	}`

	profileSchema, err := compiler.Compile([]byte(profileJSON))
	if err != nil {
		log.Fatal(err)
	}

	// Test with valid data
	profileData := map[string]interface{}{
		"user": map[string]interface{}{
			"id":    "550e8400-e29b-41d4-a716-446655440000",
			"name":  "Alice Johnson",
			"email": "alice@example.com",
		},
		"bio":     "Software engineer",
		"website": "https://alice.dev",
	}

	result := profileSchema.Validate(profileData)
	fmt.Println("Profile with registered user schema valid:", result.IsValid())
}
Output:

Profile with registered user schema valid: true

Index

Examples

Constants

View Source
const (
	FormatEmail               = "email"
	FormatDateTime            = "date-time"
	FormatDate                = "date"
	FormatTime                = "time"
	FormatURI                 = "uri"
	FormatURIRef              = "uri-reference"
	FormatUUID                = "uuid"
	FormatHostname            = "hostname"
	FormatIPv4                = "ipv4"
	FormatIPv6                = "ipv6"
	FormatRegex               = "regex"
	FormatIdnEmail            = "idn-email"
	FormatIdnHostname         = "idn-hostname"
	FormatIRI                 = "iri"
	FormatIRIRef              = "iri-reference"
	FormatURITemplate         = "uri-template"
	FormatJSONPointer         = "json-pointer"
	FormatRelativeJSONPointer = "relative-json-pointer"
	FormatDuration            = "duration"
)

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 DefaultNowFunc added in v0.4.1

func DefaultNowFunc(args ...any) (any, error)

DefaultNowFunc generates current timestamp in various formats This function must be manually registered by developers

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

func SetDefaultCompiler added in v0.4.1

func SetDefaultCompiler(c *Compiler)

SetDefaultCompiler allows setting a custom compiler for the constructor API

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 GetDefaultCompiler added in v0.4.1

func GetDefaultCompiler() *Compiler

GetDefaultCompiler returns the current default compiler

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) CompileBatch added in v0.4.2

func (c *Compiler) CompileBatch(schemas map[string][]byte) (map[string]*Schema, error)

CompileBatch compiles multiple schemas efficiently by deferring reference resolution until all schemas are compiled. This is the most efficient approach when you have many schemas with interdependencies.

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) RegisterDefaultFunc added in v0.4.1

func (c *Compiler) RegisterDefaultFunc(name string, fn DefaultFunc) *Compiler

RegisterDefaultFunc registers a function for dynamic default value generation

func (*Compiler) RegisterFormat added in v0.4.5

func (c *Compiler) RegisterFormat(name string, validator func(interface{}) bool, typeName ...string) *Compiler

RegisterFormat registers a custom format. The optional typeName parameter specifies which JSON Schema type the format applies to (e.g., "string", "number"). If omitted, the format applies to all types.

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) UnregisterFormat added in v0.4.5

func (c *Compiler) UnregisterFormat(name string) *Compiler

UnregisterFormat removes a custom format.

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 ConditionalSchema added in v0.4.0

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

ConditionalSchema represents a conditional schema for if/then/else logic

func If added in v0.4.0

func If(condition *Schema) *ConditionalSchema

If creates a conditional Schema with if/then/else keywords

func (*ConditionalSchema) Else added in v0.4.0

func (cs *ConditionalSchema) Else(otherwise *Schema) *Schema

Else sets the else clause of a conditional schema

func (*ConditionalSchema) Then added in v0.4.0

func (cs *ConditionalSchema) Then(then *Schema) *ConditionalSchema

Then sets the then clause of a conditional schema

func (*ConditionalSchema) ToSchema added in v0.4.0

func (cs *ConditionalSchema) ToSchema() *Schema

ToSchema converts a conditional schema to a regular schema

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 DefaultFunc added in v0.4.1

type DefaultFunc func(args ...any) (any, error)

DefaultFunc represents a function that can generate dynamic default values

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 FormatDef added in v0.4.5

type FormatDef struct {
	// Type specifies which JSON Schema type this format applies to (optional)
	// Supported values: "string", "number", "integer", "boolean", "array", "object"
	// Empty string means applies to all types
	Type string

	// Validate is the validation function
	Validate func(interface{}) bool
}

FormatDef defines a custom format validation rule

type FunctionCall added in v0.4.1

type FunctionCall struct {
	Name string
	Args []any
}

FunctionCall represents a parsed function call with name and arguments

type Keyword added in v0.4.0

type Keyword func(*Schema)

Keyword represents a schema keyword that can be applied to any schema

func AdditionalProps added in v0.4.0

func AdditionalProps(allowed bool) Keyword

AdditionalProps sets the additionalProperties keyword

func AdditionalPropsSchema added in v0.4.0

func AdditionalPropsSchema(schema *Schema) Keyword

AdditionalPropsSchema sets the additionalProperties keyword with a schema

func Anchor added in v0.4.0

func Anchor(anchor string) Keyword

Anchor sets the $anchor keyword

func Contains added in v0.4.0

func Contains(schema *Schema) Keyword

Contains sets the contains keyword

func ContentEncoding added in v0.4.0

func ContentEncoding(encoding string) Keyword

ContentEncoding sets the contentEncoding keyword

func ContentMediaType added in v0.4.0

func ContentMediaType(mediaType string) Keyword

ContentMediaType sets the contentMediaType keyword

func ContentSchema added in v0.4.0

func ContentSchema(schema *Schema) Keyword

ContentSchema sets the contentSchema keyword

func Default added in v0.4.0

func Default(value interface{}) Keyword

Default sets the default keyword

func Defs added in v0.4.0

func Defs(defs map[string]*Schema) Keyword

Defs sets the $defs keyword

func DependentRequired added in v0.4.0

func DependentRequired(dependencies map[string][]string) Keyword

DependentRequired sets the dependentRequired keyword

func DependentSchemas added in v0.4.0

func DependentSchemas(dependencies map[string]*Schema) Keyword

DependentSchemas sets the dependentSchemas keyword

func Deprecated added in v0.4.0

func Deprecated(deprecated bool) Keyword

Deprecated sets the deprecated keyword

func Description added in v0.4.0

func Description(desc string) Keyword

Description sets the description keyword

func DynamicAnchor added in v0.4.0

func DynamicAnchor(anchor string) Keyword

DynamicAnchor sets the $dynamicAnchor keyword

func Examples added in v0.4.0

func Examples(examples ...interface{}) Keyword

Examples sets the examples keyword

func ExclusiveMax added in v0.4.0

func ExclusiveMax(max float64) Keyword

ExclusiveMax sets the exclusiveMaximum keyword

func ExclusiveMin added in v0.4.0

func ExclusiveMin(min float64) Keyword

ExclusiveMin sets the exclusiveMinimum keyword

func Format added in v0.4.0

func Format(format string) Keyword

Format sets the format keyword

func ID added in v0.4.0

func ID(id string) Keyword

ID sets the $id keyword

func Items added in v0.4.0

func Items(itemSchema *Schema) Keyword

Items sets the items keyword

func Max added in v0.4.0

func Max(max float64) Keyword

Max sets the maximum keyword

func MaxContains added in v0.4.0

func MaxContains(max int) Keyword

MaxContains sets the maxContains keyword

func MaxItems added in v0.4.0

func MaxItems(max int) Keyword

MaxItems sets the maxItems keyword

func MaxLen added in v0.4.0

func MaxLen(max int) Keyword

MaxLen sets the maxLength keyword

func MaxProps added in v0.4.0

func MaxProps(max int) Keyword

MaxProps sets the maxProperties keyword

func Min added in v0.4.0

func Min(min float64) Keyword

Min sets the minimum keyword

func MinContains added in v0.4.0

func MinContains(min int) Keyword

MinContains sets the minContains keyword

func MinItems added in v0.4.0

func MinItems(min int) Keyword

MinItems sets the minItems keyword

func MinLen added in v0.4.0

func MinLen(min int) Keyword

MinLen sets the minLength keyword

func MinProps added in v0.4.0

func MinProps(min int) Keyword

MinProps sets the minProperties keyword

func MultipleOf added in v0.4.0

func MultipleOf(multiple float64) Keyword

MultipleOf sets the multipleOf keyword

func Pattern added in v0.4.0

func Pattern(pattern string) Keyword

Pattern sets the pattern keyword

func PatternProps added in v0.4.0

func PatternProps(patterns map[string]*Schema) Keyword

PatternProps sets the patternProperties keyword

func PrefixItems added in v0.4.0

func PrefixItems(schemas ...*Schema) Keyword

PrefixItems sets the prefixItems keyword

func PropertyNames added in v0.4.0

func PropertyNames(schema *Schema) Keyword

PropertyNames sets the propertyNames keyword

func ReadOnly added in v0.4.0

func ReadOnly(readOnly bool) Keyword

ReadOnly sets the readOnly keyword

func Required added in v0.4.0

func Required(fields ...string) Keyword

Required sets the required keyword

func SchemaURI added in v0.4.0

func SchemaURI(schemaURI string) Keyword

SchemaURI sets the $schema keyword

func Title added in v0.4.0

func Title(title string) Keyword

Title sets the title keyword

func UnevaluatedItems added in v0.4.0

func UnevaluatedItems(schema *Schema) Keyword

UnevaluatedItems sets the unevaluatedItems keyword

func UnevaluatedProps added in v0.4.0

func UnevaluatedProps(schema *Schema) Keyword

UnevaluatedProps sets the unevaluatedProperties keyword

func UniqueItems added in v0.4.0

func UniqueItems(unique bool) Keyword

UniqueItems sets the uniqueItems keyword

func WriteOnly added in v0.4.0

func WriteOnly(writeOnly bool) Keyword

WriteOnly sets the writeOnly keyword

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 Property added in v0.4.0

type Property struct {
	Name   string
	Schema *Schema
}

Property represents a Schema property definition

func Prop added in v0.4.0

func Prop(name string, schema *Schema) Property

Prop creates a property definition

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 AllOf added in v0.4.0

func AllOf(schemas ...*Schema) *Schema

AllOf creates an allOf combination Schema

func Any added in v0.4.0

func Any(keywords ...Keyword) *Schema

Any creates a Schema without type restriction

func AnyOf added in v0.4.0

func AnyOf(schemas ...*Schema) *Schema

AnyOf creates an anyOf combination Schema

func Array added in v0.4.0

func Array(keywords ...Keyword) *Schema

Array creates an array Schema with validation keywords

func Boolean added in v0.4.0

func Boolean(keywords ...Keyword) *Schema

Boolean creates a boolean Schema

func Const added in v0.4.0

func Const(value interface{}) *Schema

Const creates a const Schema

func Date added in v0.4.0

func Date() *Schema

Date creates a date format string schema

func DateTime added in v0.4.0

func DateTime() *Schema

DateTime creates a date-time format string schema

func Duration added in v0.4.0

func Duration() *Schema

Duration creates a duration format string schema

func Email added in v0.4.0

func Email() *Schema

Email creates an email format string schema

func Enum added in v0.4.0

func Enum(values ...interface{}) *Schema

Enum creates an enum Schema

func Hostname added in v0.4.0

func Hostname() *Schema

Hostname creates a hostname format string schema

func IPv4 added in v0.4.0

func IPv4() *Schema

IPv4 creates an IPv4 format string schema

func IPv6 added in v0.4.0

func IPv6() *Schema

IPv6 creates an IPv6 format string schema

func IRI added in v0.4.0

func IRI() *Schema

IRI creates an IRI format string schema

func IRIRef added in v0.4.0

func IRIRef() *Schema

IRIRef creates an IRI reference format string schema

func IdnEmail added in v0.4.0

func IdnEmail() *Schema

IdnEmail creates an internationalized email format string schema

func IdnHostname added in v0.4.0

func IdnHostname() *Schema

IdnHostname creates an internationalized hostname format string schema

func Integer added in v0.4.0

func Integer(keywords ...Keyword) *Schema

Integer creates an integer Schema with validation keywords

func JSONPointer added in v0.4.0

func JSONPointer() *Schema

JSONPointer creates a JSON pointer format string schema

func NegativeInt added in v0.4.0

func NegativeInt() *Schema

NegativeInt creates a negative integer schema

func NonNegativeInt added in v0.4.0

func NonNegativeInt() *Schema

NonNegativeInt creates a non-negative integer schema

func NonPositiveInt added in v0.4.0

func NonPositiveInt() *Schema

NonPositiveInt creates a non-positive integer schema

func Not added in v0.4.0

func Not(schema *Schema) *Schema

Not creates a not combination Schema

func Null added in v0.4.0

func Null(keywords ...Keyword) *Schema

Null creates a null Schema

func Number added in v0.4.0

func Number(keywords ...Keyword) *Schema

Number creates a number Schema with validation keywords

func Object added in v0.4.0

func Object(items ...interface{}) *Schema

Object creates an object Schema with properties and keywords

func OneOf added in v0.4.0

func OneOf(schemas ...*Schema) *Schema

OneOf creates a oneOf combination Schema

func PositiveInt added in v0.4.0

func PositiveInt() *Schema

PositiveInt creates a positive integer schema

func Ref added in v0.4.0

func Ref(ref string) *Schema

Ref creates a reference Schema using $ref keyword

func Regex added in v0.4.0

func Regex() *Schema

Regex creates a regex format string schema

func RelativeJSONPointer added in v0.4.0

func RelativeJSONPointer() *Schema

RelativeJSONPointer creates a relative JSON pointer format string schema

func String added in v0.4.0

func String(keywords ...Keyword) *Schema

String creates a string Schema with validation keywords

func Time added in v0.4.0

func Time() *Schema

Time creates a time format string schema

func URI added in v0.4.0

func URI() *Schema

URI creates a URI format string schema

func URIRef added in v0.4.0

func URIRef() *Schema

URIRef creates a URI reference format string schema

func URITemplate added in v0.4.0

func URITemplate() *Schema

URITemplate creates a URI template format string schema

func UUID added in v0.4.0

func UUID() *Schema

UUID creates a UUID format string schema

func (*Schema) GetCompiler added in v0.4.1

func (s *Schema) GetCompiler() *Compiler

GetCompiler gets the effective Compiler for the Schema Lookup order: current Schema -> parent Schema -> defaultCompiler

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) GetUnresolvedReferenceURIs added in v0.4.6

func (s *Schema) GetUnresolvedReferenceURIs() []string

GetUnresolvedReferenceURIs returns a list of URIs that this schema references but are not yet resolved

func (*Schema) MarshalJSON

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

MarshalJSON implements json.Marshaler

func (*Schema) ResolveUnresolvedReferences added in v0.4.2

func (s *Schema) ResolveUnresolvedReferences()

ResolveUnresolvedReferences tries to resolve any previously unresolved references This is called after new schemas are added to the compiler

func (*Schema) SetCompiler added in v0.4.1

func (s *Schema) SetCompiler(compiler *Compiler) *Schema

SetCompiler sets a custom Compiler for the Schema and returns the Schema itself to support method chaining

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
constructor command
custom-formats 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