jsonschema

package module
v0.7.8 Latest Latest
Warning

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

Go to latest
Published: Apr 20, 2026 License: MIT Imports: 33 Imported by: 55

README

jsonschema

Go Version License

A high-performance JSON Schema Draft 2020-12 validator for Go with direct struct validation, default-aware unmarshaling, and a fluent constructor API

Features

  • Draft 2020-12: Validate schemas and instances against the current JSON Schema specification used by the package.
  • Multiple input paths: Validate raw JSON, decoded maps, or Go structs with entry points tuned for each input type.
  • Separated workflow: Validate first, then unmarshal with defaults when the payload is safe to consume.
  • Constructor API: Build schemas in Go with Object, Prop, String, Required, and composition helpers.
  • Struct tags: Generate schemas from Go types with FromStruct and customize generation with StructTagOptions.
  • Custom formats and defaults: Register format validators and dynamic default functions on a compiler.
  • Reference support: Resolve $ref, $dynamicRef, anchors, and batch-compiled schema graphs.
  • Localized errors: Render validation output through go-i18n localizers.

Installation

go get github.com/kaptinlin/jsonschema

Requires Go 1.26+.

Quick Start

package main

import (
	"fmt"
	"log"

	"github.com/kaptinlin/jsonschema"
)

type User struct {
	Name    string `json:"name"`
	Country string `json:"country"`
}

func main() {
	schema, err := jsonschema.NewCompiler().Compile([]byte(`{
		"type": "object",
		"properties": {
			"name": {"type": "string", "minLength": 1},
			"country": {"type": "string", "default": "US"}
		},
		"required": ["name"]
	}`))
	if err != nil {
		log.Fatal(err)
	}

	data := []byte(`{"name":"Alice"}`)
	result := schema.Validate(data)
	if !result.IsValid() {
		log.Fatalf("invalid payload: %v", result.Errors)
	}

	var user User
	if err := schema.Unmarshal(&user, data); err != nil {
		log.Fatal(err)
	}

	fmt.Printf("%+v\n", user)
}

Validation Workflows

Choose the validation method that matches your input:

Input Method When to Use
[]byte ValidateJSON Raw request payloads or stored JSON documents
map[string]any ValidateMap Already-decoded JSON objects
Go struct ValidateStruct Validate Go values without a JSON round-trip
mixed Validate Convenience path that auto-detects the input type
result := schema.ValidateJSON([]byte(`{"name":"Alice"}`))
result = schema.ValidateMap(map[string]any{"name": "Alice"})
result = schema.ValidateStruct(User{Name: "Alice"})
result = schema.Validate(anyInput)

Constructor API

Build schemas directly in Go when you want type-safe composition instead of raw JSON literals.

userSchema := jsonschema.Object(
	jsonschema.Prop("name", jsonschema.String(jsonschema.MinLength(1))),
	jsonschema.Prop("email", jsonschema.Email()),
	jsonschema.Prop("age", jsonschema.Integer(jsonschema.Min(0))),
	jsonschema.Required("name", "email"),
)

result := userSchema.Validate(map[string]any{
	"name":  "Alice",
	"email": "alice@example.com",
	"age":   30,
})
fmt.Println(result.IsValid())

The constructor layer also includes composition helpers such as OneOf, AnyOf, AllOf, Not, and If(...).Then(...).Else(...).

Struct Tags and Code Generation

Generate schemas from Go types at runtime with FromStruct, or use schemagen for generated code.

type Signup struct {
	Name  string `jsonschema:"required,minLength=2,maxLength=50"`
	Email string `jsonschema:"required,format=email"`
	Age   int    `jsonschema:"minimum=18"`
}

schema, err := jsonschema.FromStruct[Signup]()
if err != nil {
	log.Fatal(err)
}

fmt.Println(schema.Validate(map[string]any{
	"name":  "Alice",
	"email": "alice@example.com",
	"age":   28,
}).IsValid())

Install the generator when you want compile-time helpers:

go install github.com/kaptinlin/jsonschema/cmd/schemagen@latest
schemagen

Use FromStructWithOptions when you need a custom tag name, schema version, required-field ordering, or schema-level properties.

Advanced Features

Custom Formats

Format validation is annotation-only by default. Turn it on explicitly and register your own validators when needed.

compiler := jsonschema.NewCompiler().SetAssertFormat(true)
compiler.RegisterFormat("customer-id", func(v any) bool {
	s, ok := v.(string)
	return ok && strings.HasPrefix(s, "CUST-")
}, "string")
Dynamic Defaults

Register default functions on a compiler, then unmarshal validated data through schemas that use those defaults.

compiler := jsonschema.NewCompiler()
compiler.RegisterDefaultFunc("now", jsonschema.DefaultNowFunc)
References, Extras, and Batch Compilation
  • Use RegisterLoader to resolve external references by scheme.
  • Use CompileBatch to compile related schemas before resolving cross-references.
  • Use SetPreserveExtra(true) when tools need to keep non-standard extension keywords in Schema.Extra.
Localized Results
i18nBundle, err := jsonschema.I18n()
if err != nil {
	log.Fatal(err)
}

localizer := i18nBundle.NewLocalizer("zh-Hans")
localized := result.ToLocalizeList(localizer)
fmt.Println(localized.Valid)

Error Handling

  • Compilation failures return regular Go errors, including sentinel errors such as ErrRegexValidation.
  • Structured error types such as RegexPatternError, StructTagError, and UnmarshalError work with errors.As.
  • Validation failures are returned in *EvaluationResult; use IsValid, Errors, ToFlag, ToList, or ToLocalizeList depending on how much detail you need.

Documentation

Development

task test    # Run the full test suite with race detection
task lint    # Run golangci-lint and tidy checks
task bench   # Run benchmarks
task verify  # Run deps, fmt, vet, lint, test, and govulncheck

For development conventions and agent-facing project rules, see AGENTS.md.

Contributing

Contributions are welcome. Open an issue for large API or behavior changes before sending a pull request.

License

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

Documentation

Overview

Package jsonschema implements a high-performance JSON Schema Draft 2020-12 validator for Go, providing direct struct validation, smart unmarshaling with defaults, and a separated validation workflow.

Compilation and unmarshaling errors are returned to callers; the package does not expose Must* entry points or public APIs that panic on invalid input.

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

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 := []any{10, 20, 30}
	result := numbersSchema.Validate(validData)
	fmt.Println("Numbers valid:", result.IsValid())

	invalidData := []any{-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]any{
		"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.MinLength(1),
			jsonschema.MaxLength(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.MinLength(1))),
			jsonschema.Prop("city", jsonschema.String(jsonschema.MinLength(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]any{
		"name":  "Alice",
		"age":   30,
		"email": "alice@example.com",
		"address": map[string]any{
			"street": "123 Main St",
			"city":   "Anytown",
			"zip":    "12345",
		},
		"tags": []any{"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]any{
		"type":     "basic",
		"features": []any{"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]any{
		"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.MinLength(1))),
		jsonschema.Prop("age", jsonschema.Integer(jsonschema.Min(0))),
		jsonschema.Required("name"),
	)

	// Valid data
	data := map[string]any{
		"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.MinLength(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.MinLength(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]any{
		"user": map[string]any{
			"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 is the `email` format.
	FormatEmail = "email"
	// FormatDateTime is the `date-time` format (RFC 3339).
	FormatDateTime = "date-time"
	// FormatDate is the `date` format (RFC 3339 full-date).
	FormatDate = "date"
	// FormatTime is the `time` format (RFC 3339 full-time).
	FormatTime = "time"
	// FormatURI is the `uri` format (RFC 3986).
	FormatURI = "uri"
	// FormatURIRef is the `uri-reference` format (RFC 3986).
	FormatURIRef = "uri-reference"
	// FormatUUID is the `uuid` format (RFC 4122).
	FormatUUID = "uuid"
	// FormatHostname is the `hostname` format (RFC 1123).
	FormatHostname = "hostname"
	// FormatIPv4 is the `ipv4` format (RFC 2673).
	FormatIPv4 = "ipv4"
	// FormatIPv6 is the `ipv6` format (RFC 4291).
	FormatIPv6 = "ipv6"
	// FormatRegex is the ECMA-262 regular expression format.
	FormatRegex = "regex"
	// FormatIdnEmail is the `idn-email` format (RFC 6531).
	FormatIdnEmail = "idn-email"
	// FormatIdnHostname is the `idn-hostname` format (RFC 5890).
	FormatIdnHostname = "idn-hostname"
	// FormatIRI is the `iri` format (RFC 3987).
	FormatIRI = "iri"
	// FormatIRIRef is the `iri-reference` format (RFC 3987).
	FormatIRIRef = "iri-reference"
	// FormatURITemplate is the `uri-template` format (RFC 6570).
	FormatURITemplate = "uri-template"
	// FormatJSONPointer is the `json-pointer` format (RFC 6901).
	FormatJSONPointer = "json-pointer"
	// FormatRelativeJSONPointer is the `relative-json-pointer` format.
	FormatRelativeJSONPointer = "relative-json-pointer"
	// FormatDuration is the `duration` format (RFC 3339 appendix A / ISO 8601).
	FormatDuration = "duration"
)

Standard JSON Schema format names from Draft 2020-12.

Variables

View Source
var (
	// ErrNoLoaderRegistered reports a missing loader for a URL scheme.
	ErrNoLoaderRegistered = errors.New("no loader registered for scheme")

	// ErrDataRead reports a data read failure.
	ErrDataRead = errors.New("data read failed")

	// ErrNetworkFetch reports a network fetch failure.
	ErrNetworkFetch = errors.New("network fetch failed")

	// ErrInvalidStatusCode reports an invalid HTTP status code.
	ErrInvalidStatusCode = errors.New("invalid http status code")

	// ErrFileWrite reports a file write failure.
	ErrFileWrite = errors.New("file write failed")

	// ErrFileCreation reports a file creation failure.
	ErrFileCreation = errors.New("file creation failed")

	// ErrDirectoryCreation reports a directory creation failure.
	ErrDirectoryCreation = errors.New("directory creation failed")

	// ErrContentWrite reports a content write failure.
	ErrContentWrite = errors.New("content write failed")

	// ErrInvalidFilenamePath reports an invalid filename path.
	ErrInvalidFilenamePath = errors.New("invalid filename path")
)
View Source
var (
	// ErrJSONUnmarshal reports a JSON unmarshal failure.
	ErrJSONUnmarshal = errors.New("json unmarshal failed")

	// ErrXMLUnmarshal reports an XML unmarshal failure.
	ErrXMLUnmarshal = errors.New("xml unmarshal failed")

	// ErrYAMLUnmarshal reports a YAML unmarshal failure.
	ErrYAMLUnmarshal = errors.New("yaml unmarshal failed")

	// ErrJSONDecode reports a JSON decode failure.
	ErrJSONDecode = errors.New("json decode failed")

	// ErrSourceEncode reports a source encoding failure.
	ErrSourceEncode = errors.New("source encode failed")

	// ErrIntermediateJSONDecode reports an intermediate JSON decode failure.
	ErrIntermediateJSONDecode = errors.New("intermediate json decode failed")

	// ErrDataEncode reports a data encoding failure.
	ErrDataEncode = errors.New("data encode failed")

	// ErrNestedValueEncode reports a nested value encoding failure.
	ErrNestedValueEncode = errors.New("nested value encode failed")
)
View Source
var (
	// ErrSchemaCompilation reports a schema compilation failure.
	ErrSchemaCompilation = errors.New("schema compilation failed")

	// ErrReferenceResolution reports a reference resolution failure.
	ErrReferenceResolution = errors.New("reference resolution failed")

	// ErrGlobalReferenceResolution reports a global reference resolution failure.
	ErrGlobalReferenceResolution = errors.New("global reference resolution failed")

	// ErrDefinitionResolution reports a `$defs` resolution failure.
	ErrDefinitionResolution = errors.New("definition resolution failed")

	// ErrItemResolution reports an array item resolution failure.
	ErrItemResolution = errors.New("item resolution failed")

	// ErrJSONPointerSegmentDecode reports a JSON Pointer segment decode failure.
	ErrJSONPointerSegmentDecode = errors.New("json pointer segment decode failed")

	// ErrJSONPointerSegmentNotFound reports a missing JSON Pointer segment.
	ErrJSONPointerSegmentNotFound = errors.New("json pointer segment not found")

	// ErrInvalidSchemaType reports an invalid schema type.
	ErrInvalidSchemaType = errors.New("invalid schema type")

	// ErrSchemaIsNil reports a nil schema.
	ErrSchemaIsNil = errors.New("schema is nil")

	// ErrSchemaInternalsIsNil reports missing schema internals.
	ErrSchemaInternalsIsNil = errors.New("schema internals is nil")

	// ErrRegexValidation reports an invalid regular expression in a schema.
	ErrRegexValidation = errors.New("regex validation failed")
)
View Source
var (
	// ErrValueValidationFailed reports a value validation failure.
	ErrValueValidationFailed = errors.New("value validation failed")

	// ErrInvalidRuleFormat reports an invalid rule format.
	ErrInvalidRuleFormat = errors.New("invalid rule format")

	// ErrRuleRequiresParameter reports a missing rule parameter.
	ErrRuleRequiresParameter = errors.New("rule requires parameter")

	// ErrEmptyRuleName reports an empty rule name.
	ErrEmptyRuleName = errors.New("empty rule name")

	// ErrValidatorAlreadyExists reports a duplicate validator registration.
	ErrValidatorAlreadyExists = errors.New("validator already exists")
)
View Source
var (
	// ErrTypeConversion reports a type conversion failure.
	ErrTypeConversion = errors.New("type conversion failed")

	// ErrTimeConversion reports a time conversion failure.
	ErrTimeConversion = errors.New("time conversion failed")

	// ErrTimeParsing reports a time parsing failure.
	ErrTimeParsing = errors.New("time parsing failed")

	// ErrRatConversion reports a rat conversion failure.
	ErrRatConversion = errors.New("rat conversion failed")

	// ErrSliceConversion reports a slice conversion failure.
	ErrSliceConversion = errors.New("slice conversion failed")

	// ErrSliceElementConversion reports a slice element conversion failure.
	ErrSliceElementConversion = errors.New("slice element conversion failed")

	// ErrFirstSliceConversion reports a first slice conversion failure.
	ErrFirstSliceConversion = errors.New("first slice conversion failed")

	// ErrSecondSliceConversion reports a second slice conversion failure.
	ErrSecondSliceConversion = errors.New("second slice conversion failed")

	// ErrNilConversion reports a nil conversion failure.
	ErrNilConversion = errors.New("nil conversion failed")

	// ErrNilPointerConversion reports a nil pointer conversion failure.
	ErrNilPointerConversion = errors.New("nil pointer conversion failed")

	// ErrValueParsing reports a value parsing failure.
	ErrValueParsing = errors.New("value parsing failed")

	// ErrValueAssignment reports a value assignment failure.
	ErrValueAssignment = errors.New("value assignment failed")

	// ErrUnsupportedType reports an unsupported type.
	ErrUnsupportedType = errors.New("unsupported type")

	// ErrUnsupportedRatType reports an unsupported rat conversion type.
	ErrUnsupportedRatType = errors.New("unsupported rat type")

	// ErrUnsupportedInputType reports an unsupported input type.
	ErrUnsupportedInputType = errors.New("unsupported input type")

	// ErrUnsupportedGenerationType reports an unsupported code generation type.
	ErrUnsupportedGenerationType = errors.New("unsupported generation type")

	// ErrUnsupportedConversion reports an unsupported conversion.
	ErrUnsupportedConversion = errors.New("unsupported conversion")

	// ErrUnrepresentableType reports an unrepresentable type.
	ErrUnrepresentableType = errors.New("unrepresentable type")

	// ErrInvalidTransformType reports an invalid transform type.
	ErrInvalidTransformType = errors.New("invalid transform type")
)
View Source
var (
	// ErrExpectedStructType reports a non-struct value where a struct was required.
	ErrExpectedStructType = errors.New("expected struct type")

	// ErrStructTagParsing reports a struct tag parsing failure.
	ErrStructTagParsing = errors.New("struct tag parsing failed")

	// ErrFieldNotFound reports a missing field.
	ErrFieldNotFound = errors.New("field not found")

	// ErrFieldAssignment reports a field assignment failure.
	ErrFieldAssignment = errors.New("field assignment failed")

	// ErrFieldAnalysis reports a field analysis failure.
	ErrFieldAnalysis = errors.New("field analysis failed")

	// ErrNilDestination reports a nil destination.
	ErrNilDestination = errors.New("destination cannot be nil")

	// ErrNotPointer reports a destination that is not a pointer.
	ErrNotPointer = errors.New("destination must be a pointer")

	// ErrNilPointer reports a nil destination pointer.
	ErrNilPointer = errors.New("destination pointer cannot be nil")
)
View Source
var (
	// ErrDefaultApplication reports a default application failure.
	ErrDefaultApplication = errors.New("default application failed")

	// ErrDefaultEvaluation reports a default evaluation failure.
	ErrDefaultEvaluation = errors.New("default evaluation failed")

	// ErrArrayDefaultApplication reports an array default application failure.
	ErrArrayDefaultApplication = errors.New("array default application failed")

	// ErrFunctionCallParsing reports a function call parsing failure.
	ErrFunctionCallParsing = errors.New("function call parsing failed")
)
View Source
var (
	// ErrNilConfig reports a nil generator config.
	ErrNilConfig = errors.New("config cannot be nil")

	// ErrAnalyzerCreation reports an analyzer creation failure.
	ErrAnalyzerCreation = errors.New("analyzer creation failed")

	// ErrWriterCreation reports a writer creation failure.
	ErrWriterCreation = errors.New("writer creation failed")

	// ErrPackageAnalysis reports a package analysis failure.
	ErrPackageAnalysis = errors.New("package analysis failed")

	// ErrCodeGeneration reports a code generation failure.
	ErrCodeGeneration = errors.New("code generation failed")

	// ErrPropertyGeneration reports a property generation failure.
	ErrPropertyGeneration = errors.New("property generation failed")

	// ErrJSONSchemaTagParsing reports a jsonschema tag parsing failure.
	ErrJSONSchemaTagParsing = errors.New("json schema tag parsing failed")

	// ErrGozodTagParsing reports a gozod tag parsing failure.
	ErrGozodTagParsing = errors.New("gozod tag parsing failed")

	// ErrTemplateLoading reports a template loading failure.
	ErrTemplateLoading = errors.New("template loading failed")

	// ErrOutputDirectoryCreation reports an output directory creation failure.
	ErrOutputDirectoryCreation = errors.New("output directory creation failed")

	// ErrFieldSchemaGeneration reports a field schema generation failure.
	ErrFieldSchemaGeneration = errors.New("field schema generation failed")

	// ErrTemplateExecution reports a template execution failure.
	ErrTemplateExecution = errors.New("template execution failed")

	// ErrMainTemplateParsing reports a main template parsing failure.
	ErrMainTemplateParsing = errors.New("main template parsing failed")

	// ErrDependencyAnalysis reports a dependency analysis failure.
	ErrDependencyAnalysis = errors.New("dependency analysis failed")

	// ErrTemplateParsing reports a template parsing failure.
	ErrTemplateParsing = errors.New("template parsing failed")

	// ErrCodeFormatting reports a code formatting failure.
	ErrCodeFormatting = errors.New("code formatting failed")

	// ErrStructNodeNotFound reports a missing struct node.
	ErrStructNodeNotFound = errors.New("struct node not found")
)
View Source
var (
	// ErrArrayItemNotSchema reports a non-schema array item.
	ErrArrayItemNotSchema = errors.New("array item not schema")

	// ErrExpectedArrayOrSlice reports a value that is not an array or slice.
	ErrExpectedArrayOrSlice = errors.New("expected array or slice")

	// ErrNilPointerToArray reports a nil pointer to an array value.
	ErrNilPointerToArray = errors.New("nil pointer to array")

	// ErrNilPointerToRecord reports a nil pointer to a record value.
	ErrNilPointerToRecord = errors.New("nil pointer to record")

	// ErrNilPointerToObject reports a nil pointer to an object value.
	ErrNilPointerToObject = errors.New("nil pointer to object")

	// ErrExpectedMapStringAny reports a value that is not map[string]any.
	ErrExpectedMapStringAny = errors.New("expected map[string]any")

	// ErrNonStringKeyFound reports a non-string map key.
	ErrNonStringKeyFound = errors.New("non-string key found in map")
)
View Source
var (
	// ErrValueOverflows reports an overflow in the target type.
	ErrValueOverflows = errors.New("value overflows target type")

	// ErrEmptyInput reports an empty input.
	ErrEmptyInput = errors.New("empty input")

	// ErrNegativeValueConversion reports a negative value conversion failure.
	ErrNegativeValueConversion = errors.New("negative value conversion failed")

	// ErrNonWholeNumber reports a non-whole number.
	ErrNonWholeNumber = errors.New("not a whole number")

	// ErrInvalidSliceArrayString reports a value that is not a slice, array, or string.
	ErrInvalidSliceArrayString = errors.New("invalid slice array string")

	// ErrNilValue reports a nil value.
	ErrNilValue = errors.New("nil value")

	// ErrNilConstValue reports an unmarshal into a nil ConstValue.
	ErrNilConstValue = errors.New("cannot unmarshal into nil ConstValue")

	// ErrIPv6AddressFormat reports an invalid IPv6 address format.
	ErrIPv6AddressFormat = errors.New("ipv6 address format error")

	// ErrInvalidIPv6 reports an invalid IPv6 address.
	ErrInvalidIPv6 = errors.New("invalid ipv6 address")
)
View Source
var (
	// ErrAbsolutePathResolution reports an absolute path resolution failure.
	ErrAbsolutePathResolution = errors.New("absolute path resolution failed")

	// ErrCurrentDirectoryAccess reports a current directory access failure.
	ErrCurrentDirectoryAccess = errors.New("current directory access failed")

	// ErrPathOutsideDirectory reports a path outside the current directory.
	ErrPathOutsideDirectory = errors.New("path outside directory")
)
View Source
var (
	// ErrUnderlyingError reports an underlying error without additional context.
	ErrUnderlyingError = errors.New("underlying error")
)
View Source
var Formats = map[string]func(any) 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(any) 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 CacheStats added in v0.6.11

func CacheStats() map[string]int

CacheStats returns statistics about the global schema cache - useful for monitoring

func ClearSchemaCache added in v0.4.7

func ClearSchemaCache()

ClearSchemaCache clears the global schema cache - useful for testing and memory management

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 I18n added in v0.6.11

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

I18n returns an initialized internationalization bundle with embedded locales

func IsDate

func IsDate(v any) 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 any) 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 any) 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 any) 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 any) 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 any) 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 any) 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 any) 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 any) 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 any) bool

IsRegex tells whether given string is a valid regex pattern

func IsRelativeJSONPointer

func IsRelativeJSONPointer(v any) 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 any) 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 any) bool

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

func IsURIReference

func IsURIReference(v any) 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 any) bool

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

Current implementation does minimal validation.

func IsUUID

func IsUUID(v any) 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 RegisterCustomValidator added in v0.4.7

func RegisterCustomValidator(name string, validator CustomValidatorFunc)

RegisterCustomValidator registers a custom validator globally

func SetDefaultCompiler added in v0.4.1

func SetDefaultCompiler(c *Compiler)

SetDefaultCompiler sets the compiler used by 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) (any, 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.
	// PreserveExtra indicates whether to preserve unknown keywords in the schema.
	// If false (default), unknown keywords are stripped during compilation.
	PreserveExtra bool
	// contains filtered or unexported fields
}

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

func DefaultCompiler added in v0.6.11

func DefaultCompiler() *Compiler

DefaultCompiler returns the compiler used by the constructor API.

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) 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(any) 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) (any, error)) *Compiler

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

func (*Compiler) Schema added in v0.6.11

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

Schema 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) 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) SetPreserveExtra added in v0.6.8

func (c *Compiler) SetPreserveExtra(preserve bool) *Compiler

SetPreserveExtra sets whether to preserve unknown keywords in the schema.

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 any) error) *Compiler

WithDecoderJSON configures custom JSON decoder implementation.

func (*Compiler) WithEncoderJSON added in v0.2.3

func (c *Compiler) WithEncoderJSON(encoder func(v any) ([]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 builds `if`/`then`/`else` schemas.

func If added in v0.4.0

func If(condition *Schema) *ConditionalSchema

If begins an `if`/`then`/`else` schema.

func (*ConditionalSchema) Else added in v0.4.0

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

Else sets the `else` branch and returns the completed schema.

func (*ConditionalSchema) Then added in v0.4.0

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

Then sets the `then` branch.

func (*ConditionalSchema) ToSchema added in v0.4.0

func (cs *ConditionalSchema) ToSchema() *Schema

ToSchema returns the conditional schema as a regular schema.

type ConstValue

type ConstValue struct {
	Value any
	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 CustomValidatorFunc added in v0.4.7

type CustomValidatorFunc func(_ reflect.Type, params []string) []Keyword

CustomValidatorFunc represents a custom validator function

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) Contains added in v0.4.14

func (ds *DynamicScope) Contains(schema *Schema) bool

Contains checks if a schema is already in the dynamic scope (circular reference detection).

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]any `json:"params"`
}

EvaluationError represents an error that occurred during schema evaluation

func NewEvaluationError

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

NewEvaluationError creates a new evaluation error with the specified details

func (*EvaluationError) Error

func (e *EvaluationError) Error() string

Error returns a string representation of the evaluation error.

func (*EvaluationError) Localize

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

Localize returns a localized error message using the provided localizer.

type EvaluationResult

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

EvaluationResult represents the complete result of a schema validation

func NewEvaluationResult

func NewEvaluationResult(schema *Schema) *EvaluationResult

NewEvaluationResult creates a new evaluation result for the given schema

func (*EvaluationResult) AddAnnotation

func (e *EvaluationResult) AddAnnotation(keyword string, annotation any) *EvaluationResult

AddAnnotation adds an annotation to this result

func (*EvaluationResult) AddDetail

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

AddDetail adds a detailed evaluation result to this result

func (*EvaluationResult) AddError

AddError adds an evaluation error to this result

func (*EvaluationResult) CollectAnnotations

func (e *EvaluationResult) CollectAnnotations() *EvaluationResult

CollectAnnotations collects annotations from child results

func (*EvaluationResult) DetailedErrors added in v0.6.11

func (e *EvaluationResult) DetailedErrors(localizer ...*i18n.Localizer) map[string]string

DetailedErrors collects all detailed validation errors from the nested Details hierarchy. This method helps users access specific validation failures that might be buried in nested structures. Returns a map where keys are field paths and values are the most specific error messages. For localized messages, pass a localizer; for default English messages, call without arguments.

func (*EvaluationResult) IsValid

func (e *EvaluationResult) IsValid() bool

IsValid returns whether this result is valid

func (*EvaluationResult) SetEvaluationPath

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

SetEvaluationPath sets the evaluation path for this result

func (*EvaluationResult) SetInstanceLocation

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

SetInstanceLocation sets the instance location for this result

func (*EvaluationResult) SetInvalid

func (e *EvaluationResult) SetInvalid() *EvaluationResult

SetInvalid marks this result as invalid

func (*EvaluationResult) SetSchemaLocation

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

SetSchemaLocation sets the schema location for this result

func (*EvaluationResult) ToFlag

func (e *EvaluationResult) ToFlag() *Flag

ToFlag 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
	Omitzero  bool         // Whether the field has omitzero tag
	Type      reflect.Type // Field type
}

FieldInfo contains metadata for a struct field

type Flag

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

Flag represents a simple validation result with just validity status

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(any) 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 applies a JSON Schema keyword to a schema built with the constructor API.

func AdditionalProps added in v0.4.0

func AdditionalProps(allowed bool) Keyword

AdditionalProps sets `additionalProperties` to a boolean schema.

func AdditionalPropsSchema added in v0.4.0

func AdditionalPropsSchema(schema *Schema) Keyword

AdditionalPropsSchema sets `additionalProperties` to a schema.

func Anchor added in v0.4.0

func Anchor(anchor string) Keyword

Anchor sets `$anchor`.

func Contains added in v0.4.0

func Contains(schema *Schema) Keyword

Contains sets `contains`.

func ContentEncoding added in v0.4.0

func ContentEncoding(encoding string) Keyword

ContentEncoding sets `contentEncoding`.

func ContentMediaType added in v0.4.0

func ContentMediaType(mediaType string) Keyword

ContentMediaType sets `contentMediaType`.

func ContentSchema added in v0.4.0

func ContentSchema(schema *Schema) Keyword

ContentSchema sets `contentSchema`.

func Default added in v0.4.0

func Default(value any) Keyword

Default sets `default`.

func Defs added in v0.4.0

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

Defs sets `$defs`.

func DependentRequired added in v0.4.0

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

DependentRequired sets `dependentRequired`.

func DependentSchemas added in v0.4.0

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

DependentSchemas sets `dependentSchemas`.

func Deprecated added in v0.4.0

func Deprecated(deprecated bool) Keyword

Deprecated sets `deprecated`.

func Description added in v0.4.0

func Description(desc string) Keyword

Description sets `description`.

func DynamicAnchor added in v0.4.0

func DynamicAnchor(anchor string) Keyword

DynamicAnchor sets `$dynamicAnchor`.

func Examples added in v0.4.0

func Examples(examples ...any) Keyword

Examples sets `examples`.

func ExclusiveMax added in v0.4.0

func ExclusiveMax(maxVal float64) Keyword

ExclusiveMax sets `exclusiveMaximum`.

func ExclusiveMin added in v0.4.0

func ExclusiveMin(minVal float64) Keyword

ExclusiveMin sets `exclusiveMinimum`.

func Format added in v0.4.0

func Format(format string) Keyword

Format sets `format`.

func ID added in v0.4.0

func ID(id string) Keyword

ID sets `$id`.

func Items added in v0.4.0

func Items(itemSchema *Schema) Keyword

Items sets `items`.

func Max added in v0.4.0

func Max(maxVal float64) Keyword

Max sets `maximum`.

func MaxContains added in v0.4.0

func MaxContains(maxContains int) Keyword

MaxContains sets `maxContains`.

func MaxItems added in v0.4.0

func MaxItems(maxItems int) Keyword

MaxItems sets `maxItems`.

func MaxLength added in v0.6.15

func MaxLength(maxLen int) Keyword

MaxLength sets `maxLength`.

func MaxProps added in v0.4.0

func MaxProps(maxProps int) Keyword

MaxProps sets `maxProperties`.

func Min added in v0.4.0

func Min(minVal float64) Keyword

Min sets `minimum`.

func MinContains added in v0.4.0

func MinContains(minContains int) Keyword

MinContains sets `minContains`.

func MinItems added in v0.4.0

func MinItems(minItems int) Keyword

MinItems sets `minItems`.

func MinLength added in v0.6.15

func MinLength(minLen int) Keyword

MinLength sets `minLength`.

func MinProps added in v0.4.0

func MinProps(minProps int) Keyword

MinProps sets `minProperties`.

func MultipleOf added in v0.4.0

func MultipleOf(multiple float64) Keyword

MultipleOf sets `multipleOf`.

func Pattern added in v0.4.0

func Pattern(pattern string) Keyword

Pattern sets `pattern`.

func PatternProps added in v0.4.0

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

PatternProps sets `patternProperties`.

func PrefixItems added in v0.4.0

func PrefixItems(schemas ...*Schema) Keyword

PrefixItems sets `prefixItems`.

func PropertyNames added in v0.4.0

func PropertyNames(schema *Schema) Keyword

PropertyNames sets `propertyNames`.

func ReadOnly added in v0.4.0

func ReadOnly(readOnly bool) Keyword

ReadOnly sets `readOnly`.

func Required added in v0.4.0

func Required(fields ...string) Keyword

Required sets `required`.

func SchemaURI added in v0.4.0

func SchemaURI(schemaURI string) Keyword

SchemaURI sets `$schema`.

func Title added in v0.4.0

func Title(title string) Keyword

Title sets `title`.

func UnevaluatedItems added in v0.4.0

func UnevaluatedItems(schema *Schema) Keyword

UnevaluatedItems sets `unevaluatedItems`.

func UnevaluatedProps added in v0.4.0

func UnevaluatedProps(schema *Schema) Keyword

UnevaluatedProps sets `unevaluatedProperties`.

func UniqueItems added in v0.4.0

func UniqueItems(unique bool) Keyword

UniqueItems sets `uniqueItems`.

func WriteOnly added in v0.4.0

func WriteOnly(writeOnly bool) Keyword

WriteOnly sets `writeOnly`.

type List

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

List represents a flat list of validation errors

type Property added in v0.4.0

type Property struct {
	Name   string
	Schema *Schema
}

Property pairs a property name with its schema.

func Prop added in v0.4.0

func Prop(name string, schema *Schema) Property

Prop returns a named property for Object.

type Rat

type Rat struct {
	*big.Rat
}

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

func NewRat

func NewRat(value any) *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 RegexPatternError added in v0.6.0

type RegexPatternError struct {
	// Keyword identifies the JSON Schema keyword containing the invalid pattern.
	// Examples: "pattern", "patternProperties".
	Keyword string

	// Location is the JSON Pointer path to the keyword instance.
	// Example: "#/properties/email/pattern".
	Location string

	// Pattern is the regex pattern that failed to compile.
	Pattern string

	// Err is the underlying regexp compilation error.
	Err error
}

RegexPatternError provides structured context for invalid regular expressions discovered during schema compilation.

func (*RegexPatternError) Error added in v0.6.0

func (e *RegexPatternError) Error() string

Error formats the regex compilation error with keyword, location, and pattern context.

func (*RegexPatternError) Unwrap added in v0.6.0

func (e *RegexPatternError) Unwrap() error

Unwrap returns the underlying regexp compilation error.

type RequiredSort added in v0.5.1

type RequiredSort string

RequiredSort controls how required field names are ordered

const (
	// RequiredSortAlphabetical sorts required fields alphabetically for deterministic output
	RequiredSortAlphabetical RequiredSort = "alphabetical"

	// RequiredSortNone does not sort required fields, preserving the order from struct field iteration
	// Note: May be non-deterministic due to map iteration in TagParser
	RequiredSortNone RequiredSort = "none"
)

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  []any       `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     any     `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    []any   `json:"examples,omitempty"`    // Examples of the instance data that validates against this schema.

	// Extra keywords not in specification
	Extra map[string]any `json:"-"`
	// 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 returns a schema with `allOf` set to schemas.

func Any added in v0.4.0

func Any(keywords ...Keyword) *Schema

Any returns a schema with no type restriction.

func AnyOf added in v0.4.0

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

AnyOf returns a schema with `anyOf` set to schemas.

func Array added in v0.4.0

func Array(keywords ...Keyword) *Schema

Array returns an array schema with the given keywords.

func Boolean added in v0.4.0

func Boolean(keywords ...Keyword) *Schema

Boolean returns a boolean schema with the given keywords.

func Const added in v0.4.0

func Const(value any) *Schema

Const returns a schema with `const` set to value.

func Date added in v0.4.0

func Date() *Schema

Date returns a string schema with the `date` format.

func DateTime added in v0.4.0

func DateTime() *Schema

DateTime returns a string schema with the `date-time` format.

func Duration added in v0.4.0

func Duration() *Schema

Duration returns a string schema with the `duration` format.

func Email added in v0.4.0

func Email() *Schema

Email returns a string schema with the `email` format.

func Enum added in v0.4.0

func Enum(values ...any) *Schema

Enum returns a schema with `enum` set to values.

func FromStruct added in v0.4.7

func FromStruct[T any]() (*Schema, error)

FromStruct generates a JSON Schema from a struct type with jsonschema tags.

func FromStructWithOptions added in v0.4.7

func FromStructWithOptions[T any](options *StructTagOptions) (*Schema, error)

FromStructWithOptions generates a JSON Schema from a struct type with custom options.

func Hostname added in v0.4.0

func Hostname() *Schema

Hostname returns a string schema with the `hostname` format.

func IPv4 added in v0.4.0

func IPv4() *Schema

IPv4 returns a string schema with the `ipv4` format.

func IPv6 added in v0.4.0

func IPv6() *Schema

IPv6 returns a string schema with the `ipv6` format.

func IRI added in v0.4.0

func IRI() *Schema

IRI returns a string schema with the `iri` format.

func IRIRef added in v0.4.0

func IRIRef() *Schema

IRIRef returns a string schema with the `iri-reference` format.

func IdnEmail added in v0.4.0

func IdnEmail() *Schema

IdnEmail returns a string schema with the `idn-email` format.

func IdnHostname added in v0.4.0

func IdnHostname() *Schema

IdnHostname returns a string schema with the `idn-hostname` format.

func Integer added in v0.4.0

func Integer(keywords ...Keyword) *Schema

Integer returns an integer schema with the given keywords.

func JSONPointer added in v0.4.0

func JSONPointer() *Schema

JSONPointer returns a string schema with the `json-pointer` format.

func NegativeInt added in v0.4.0

func NegativeInt() *Schema

NegativeInt returns an integer schema with `maximum` set to -1.

func NonNegativeInt added in v0.4.0

func NonNegativeInt() *Schema

NonNegativeInt returns an integer schema with `minimum` set to 0.

func NonPositiveInt added in v0.4.0

func NonPositiveInt() *Schema

NonPositiveInt returns an integer schema with `maximum` set to 0.

func Not added in v0.4.0

func Not(schema *Schema) *Schema

Not returns a schema with `not` set to schema.

func Null added in v0.4.0

func Null(keywords ...Keyword) *Schema

Null returns a null schema with the given keywords.

func Number added in v0.4.0

func Number(keywords ...Keyword) *Schema

Number returns a number schema with the given keywords.

func Object added in v0.4.0

func Object(items ...any) *Schema

Object returns an object schema built from properties and keywords.

func OneOf added in v0.4.0

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

OneOf returns a schema with `oneOf` set to schemas.

func PositiveInt added in v0.4.0

func PositiveInt() *Schema

PositiveInt returns an integer schema with `minimum` set to 1.

func Ref added in v0.4.0

func Ref(ref string) *Schema

Ref returns a schema with `$ref` set to ref.

func Regex added in v0.4.0

func Regex() *Schema

Regex returns a string schema with the `regex` format.

func RelativeJSONPointer added in v0.4.0

func RelativeJSONPointer() *Schema

RelativeJSONPointer returns a string schema with the `relative-json-pointer` format.

func String added in v0.4.0

func String(keywords ...Keyword) *Schema

String returns a string schema with the given keywords.

func Time added in v0.4.0

func Time() *Schema

Time returns a string schema with the `time` format.

func URI added in v0.4.0

func URI() *Schema

URI returns a string schema with the `uri` format.

func URIRef added in v0.4.0

func URIRef() *Schema

URIRef returns a string schema with the `uri-reference` format.

func URITemplate added in v0.4.0

func URITemplate() *Schema

URITemplate returns a string schema with the `uri-template` format.

func UUID added in v0.4.0

func UUID() *Schema

UUID returns a string schema with the `uuid` format.

func (*Schema) Compiler added in v0.6.11

func (s *Schema) Compiler() *Compiler

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

func (*Schema) MarshalJSON

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

MarshalJSON implements json.Marshaler

func (*Schema) MarshalJSONTo added in v0.4.14

func (s *Schema) MarshalJSONTo(enc *jsontext.Encoder, opts json.Options) error

MarshalJSONTo implements json.MarshalerTo for JSON v2 with proper option support

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) SchemaLocation added in v0.6.11

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

SchemaLocation returns the schema location with the given anchor

func (*Schema) SchemaURI added in v0.6.11

func (s *Schema) SchemaURI() string

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

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 any) 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]any (parsed JSON object)
  • Go structs and other types

Supported destination types:

  • *struct (Go struct pointer)
  • *map[string]any (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) UnresolvedReferenceURIs added in v0.6.11

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

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

func (*Schema) Validate

func (s *Schema) Validate(instance any) *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]any) *EvaluationResult

ValidateMap validates map[string]any 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 any) *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) MarshalJSONTo added in v0.4.14

func (sm *SchemaMap) MarshalJSONTo(enc *jsontext.Encoder, opts json.Options) error

MarshalJSONTo implements json.MarshalerTo for JSON v2 with proper option support

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 (st SchemaType) MarshalJSON() ([]byte, error)

MarshalJSON customizes the JSON serialization of SchemaType.

func (*SchemaType) UnmarshalJSON added in v0.2.0

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

UnmarshalJSON customizes the JSON deserialization into SchemaType.

type StructTagError added in v0.4.7

type StructTagError struct {
	StructType string // The type name of the struct being processed
	FieldName  string // The name of the field with the error
	TagRule    string // The tag rule that failed (e.g., "pattern=...")
	Message    string // Human-readable error message
	Err        error  // Underlying error (renamed from Cause for consistency with UnmarshalError)
}

StructTagError represents an error that occurred during struct tag processing. It provides detailed context about which struct, field, and tag rule caused the error.

func (*StructTagError) Error added in v0.4.7

func (e *StructTagError) Error() string

Error returns a formatted error message with full context.

func (*StructTagError) Unwrap added in v0.4.7

func (e *StructTagError) Unwrap() error

Unwrap returns the underlying error, allowing error chain inspection with errors.Is/As.

type StructTagOptions added in v0.4.7

type StructTagOptions struct {
	TagName             string              // tag name to parse (default: "jsonschema")
	AllowUntaggedFields bool                // whether to include fields without tags (default: false)
	DefaultRequired     bool                // whether fields are required by default (default: false)
	FieldNameMapper     func(string) string // function to map Go field names to JSON names
	CustomValidators    map[string]any      // custom validators (for future extension)
	CacheEnabled        bool                // whether to enable schema caching (default: true)
	SchemaVersion       string              // $schema URI to include in generated schemas (empty string = omit $schema, default = Draft 2020-12)
	RequiredSort        RequiredSort        // controls ordering of required fields (default: RequiredSortAlphabetical)

	// Schema-level properties using map approach
	SchemaProperties map[string]any // flexible configuration for any schema property
}

StructTagOptions holds configuration for struct tag schema generation

func DefaultStructTagOptions added in v0.4.7

func DefaultStructTagOptions() *StructTagOptions

DefaultStructTagOptions returns the default configuration for struct tag processing

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

Error returns a string representation of the unmarshal error.

func (*UnmarshalError) Unwrap added in v0.2.6

func (e *UnmarshalError) Unwrap() error

Unwrap returns the underlying error.

type ValidatorRegistry added in v0.4.7

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

ValidatorRegistry manages custom validators

func (*ValidatorRegistry) CustomValidator added in v0.6.11

func (r *ValidatorRegistry) CustomValidator(name string) (CustomValidatorFunc, bool)

CustomValidator retrieves a custom validator by name

Directories

Path Synopsis
cmd
schemagen command
Package main implements the schemagen code generation tool.
Package main implements the schemagen code generation tool.
examples
basic command
Package main demonstrates basic usage of the jsonschema library.
Package main demonstrates basic usage of the jsonschema library.
constructor command
Package main demonstrates constructor usage of the jsonschema library.
Package main demonstrates constructor usage of the jsonschema library.
custom-formats command
Package main demonstrates custom-formats usage of the jsonschema library.
Package main demonstrates custom-formats usage of the jsonschema library.
dynamic-defaults command
Package main demonstrates dynamic default value generation with the jsonschema library.
Package main demonstrates dynamic default value generation with the jsonschema library.
error-handling command
Package main demonstrates error-handling usage of the jsonschema library.
Package main demonstrates error-handling usage of the jsonschema library.
i18n command
Package main demonstrates i18n usage of the jsonschema library.
Package main demonstrates i18n usage of the jsonschema library.
multilingual-errors command
Package main demonstrates multilingual-errors usage of the jsonschema library.
Package main demonstrates multilingual-errors usage of the jsonschema library.
multiple-input-types command
Package main demonstrates multiple-input-types usage of the jsonschema library.
Package main demonstrates multiple-input-types usage of the jsonschema library.
struct-validation command
Package main demonstrates struct-validation usage of the jsonschema library.
Package main demonstrates struct-validation usage of the jsonschema library.
unmarshaling command
Package main demonstrates unmarshaling usage of the jsonschema library.
Package main demonstrates unmarshaling usage of the jsonschema library.
pkg
tagparser
Package tagparser provides shared tag parsing functionality for schemagen.
Package tagparser provides shared tag parsing functionality for schemagen.

Jump to

Keyboard shortcuts

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