jsonstructure

package module
v0.5.5 Latest Latest
Warning

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

Go to latest
Published: Dec 9, 2025 License: MIT Imports: 10 Imported by: 0

README

JSON Structure SDK for Go

A Go implementation of validators for JSON Structure schemas and instances.

Installation

go get github.com/json-structure/sdk/go

Thread Safety

Both SchemaValidator and InstanceValidator are safe for concurrent use from multiple goroutines after construction. A single validator instance can be shared across goroutines to validate multiple schemas or instances simultaneously without risk of data races or error leakage between validations.

// Create a single validator instance
validator := jsonstructure.NewInstanceValidator(&jsonstructure.InstanceValidatorOptions{
    Extended: true,
})

// Safe to use from multiple goroutines concurrently
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
    wg.Add(1)
    go func() {
        defer wg.Done()
        result := validator.Validate(instance, schema)
        // Process result...
    }()
}
wg.Wait()

This design follows idiomatic Go patterns where validators maintain only immutable configuration state after construction, while all mutable validation state is managed internally within each validation operation.

Usage

Schema Validation

Validate a JSON Structure schema document:

package main

import (
	"encoding/json"
	"fmt"

	jsonstructure "github.com/json-structure/sdk/go"
)

func main() {
	// Parse a schema
	schemaJSON := `{
		"type": "object",
		"properties": {
			"name": { "type": "string", "maxLength": 100 },
			"age": { "type": "int8" }
		},
		"required": ["name"]
	}`

	var schema map[string]interface{}
	json.Unmarshal([]byte(schemaJSON), &schema)

	// Validate the schema
	options := &jsonstructure.SchemaValidatorOptions{
		EnabledExtensions: map[string]bool{
			"JSONStructureValidation": true,
		},
	}
	validator := jsonstructure.NewSchemaValidator(options)

	result := validator.Validate(schema)

	if result.IsValid {
		fmt.Println("Schema is valid!")
	} else {
		fmt.Println("Schema validation errors:")
		for _, err := range result.Errors {
			fmt.Printf("  %s: %s\n", err.Path, err.Message)
		}
	}
}
Instance Validation

Validate a JSON instance against a schema:

package main

import (
	"fmt"

	jsonstructure "github.com/json-structure/sdk/go"
)

func main() {
	// Define a schema
	schema := map[string]interface{}{
		"type": "object",
		"properties": map[string]interface{}{
			"name": map[string]interface{}{
				"type":      "string",
				"maxLength": float64(100),
			},
			"age": map[string]interface{}{
				"type":    "int8",
				"minimum": float64(0),
				"maximum": float64(120),
			},
			"email": map[string]interface{}{
				"type": "string",
			},
		},
		"required": []interface{}{"name", "email"},
	}

	// Create an instance validator with extended validation enabled
	options := &jsonstructure.InstanceValidatorOptions{
		EnabledExtensions: map[string]bool{
			"JSONStructureValidation": true,
		},
	}
	validator := jsonstructure.NewInstanceValidator(options)

	// Valid instance
	validInstance := map[string]interface{}{
		"name":  "Alice",
		"age":   float64(30),
		"email": "alice@example.com",
	}

	result := validator.Validate(validInstance, schema)
	if result.IsValid {
		fmt.Println("Instance is valid!")
	}

	// Invalid instance (missing required field, age out of range)
	invalidInstance := map[string]interface{}{
		"name": "Bob",
		"age":  float64(150),
	}

	result = validator.Validate(invalidInstance, schema)
	if !result.IsValid {
		fmt.Println("Instance validation errors:")
		for _, err := range result.Errors {
			fmt.Printf("  %s: %s\n", err.Path, err.Message)
		}
	}
}
JSON String Validation

Validate JSON strings directly using the convenience methods:

package main

import (
	"fmt"

	jsonstructure "github.com/json-structure/sdk/go"
)

func main() {
	schemaJSON := []byte(`{
		"type": "object",
		"properties": {
			"name": {"type": "string"},
			"age": {"type": "int32"}
		},
		"required": ["name"]
	}`)

	instanceJSON := []byte(`{"name": "Alice", "age": 30}`)

	validator := jsonstructure.NewInstanceValidator(nil)
	result, err := validator.ValidateJSON(instanceJSON, schemaJSON)
	if err != nil {
		fmt.Printf("JSON parse error: %v\n", err)
		return
	}

	fmt.Printf("Valid: %v\n", result.IsValid)
}

Serialization Helpers

The SDK provides wrapper types for correct JSON Structure serialization. Per the spec, certain types must be serialized as strings because JSON numbers (IEEE 754 double) cannot accurately represent their full range.

Types that serialize as strings:
  • Int64String, UInt64String - 64-bit integers as strings
  • BigIntString - 128-bit integers (*big.Int) as strings
  • DecimalString - Decimal numbers as strings
  • Duration - ISO 8601 duration format (e.g., "PT1H30M")
  • Date, TimeOfDay, DateTime - ISO 8601/RFC 3339 formats
  • Binary - Base64 encoded
  • UUID, URI, JSONPointer - String representations
Example Usage
package main

import (
	"encoding/json"
	"fmt"
	"time"

	js "github.com/json-structure/sdk/go"
)

type Person struct {
	Name      string          `json:"name"`
	ID        js.Int64String  `json:"id"`        // Serializes as "9223372036854775807"
	Balance   js.BigIntString `json:"balance"`   // Large int as string
	BirthDate js.Date         `json:"birthDate"` // "2000-01-15"
	Duration  js.Duration     `json:"duration"`  // "PT1H30M"
	Data      js.Binary       `json:"data"`      // Base64 encoded
}

func main() {
	bigInt, _ := js.NewBigIntStringFromString("170141183460469231731687303715884105727")
	
	p := Person{
		Name:      "Alice",
		ID:        js.Int64String(9223372036854775807),
		Balance:   bigInt,
		BirthDate: js.NewDate(2000, time.January, 15),
		Duration:  js.Duration(time.Hour + 30*time.Minute),
		Data:      js.Binary([]byte("Hello")),
	}

	data, _ := json.Marshal(p)
	fmt.Println(string(data))
	// Output: {"name":"Alice","id":"9223372036854775807","balance":"170141183460469231731687303715884105727","birthDate":"2000-01-15","duration":"PT1H30M","data":"SGVsbG8="}

	// Round-trip deserialization
	var p2 Person
	json.Unmarshal(data, &p2)
	fmt.Printf("ID: %d\n", p2.ID.Value()) // ID: 9223372036854775807
}

## Sideloading External Schemas

When using `$import` to reference external schemas, you can provide those schemas
directly instead of fetching them from URIs:

```go
package main

import (
	"fmt"

	jsonstructure "github.com/json-structure/sdk/go"
)

func main() {
	// External schema that would normally be fetched
	addressSchema := map[string]interface{}{
		"$schema": "https://json-structure.org/meta/core/v0/#",
		"$id":     "https://example.com/address.json",
		"type":    "object",
		"properties": map[string]interface{}{
			"street": map[string]interface{}{"type": "string"},
			"city":   map[string]interface{}{"type": "string"},
		},
	}

	// Main schema that imports the address schema
	mainSchema := map[string]interface{}{
		"$schema": "https://json-structure.org/meta/core/v0/#",
		"type":    "object",
		"properties": map[string]interface{}{
			"name":    map[string]interface{}{"type": "string"},
			"address": map[string]interface{}{"type": map[string]interface{}{"$ref": "#/definitions/Imported/Address"}},
		},
		"definitions": map[string]interface{}{
			"Imported": map[string]interface{}{
				"$import": "https://example.com/address.json",
			},
		},
	}

	// Sideload the address schema - keyed by URI
	options := &jsonstructure.SchemaValidatorOptions{
		AllowImport: true,
		ExternalSchemas: map[string]interface{}{
			"https://example.com/address.json": addressSchema,
		},
	}
	validator := jsonstructure.NewSchemaValidator(options)

	result := validator.Validate(mainSchema)
	fmt.Printf("Valid: %v\n", result.IsValid)
}

API Reference

Types
ValidationResult
type ValidationResult struct {
	IsValid bool              // Whether validation passed
	Errors  []ValidationError // List of validation errors
}
ValidationError
type ValidationError struct {
	Path    string // JSON Pointer path to the error
	Message string // Human-readable error description
}
SchemaValidatorOptions
type SchemaValidatorOptions struct {
	EnabledExtensions map[string]bool            // e.g., {"JSONStructureValidation": true}
	AllowImport       bool                       // Enable $import/$importdefs processing
	ExternalSchemas   map[string]interface{}     // URI to schema map for import resolution
}
InstanceValidatorOptions
type InstanceValidatorOptions struct {
	EnabledExtensions map[string]bool            // Enable extended validation features
	AllowImport       bool                       // Enable $import/$importdefs processing
	ExternalSchemas   map[string]interface{}     // URI to schema map for import resolution
}
SchemaValidator
func NewSchemaValidator(options *SchemaValidatorOptions) *SchemaValidator
func (v *SchemaValidator) Validate(schema interface{}) ValidationResult
func (v *SchemaValidator) ValidateJSON(schemaData []byte) (ValidationResult, error)
InstanceValidator
func NewInstanceValidator(options *InstanceValidatorOptions) *InstanceValidator
func (v *InstanceValidator) Validate(instance interface{}, schema interface{}) ValidationResult
func (v *InstanceValidator) ValidateJSON(instanceData, schemaData []byte) (ValidationResult, error)

Supported Types

Primitive Types
  • string - Unicode string
  • boolean - true/false
  • null - null value
  • int8, uint8, int16, uint16, int32, uint32, int64, uint64, int128, uint128 - Fixed-size integers
  • float, float8, double, decimal - Floating-point numbers
  • number, integer - Generic numeric types
  • date, datetime, time, duration - Temporal types (ISO 8601)
  • uuid - UUID (RFC 4122)
  • uri - URI (RFC 3986)
  • binary - Base64-encoded binary
  • jsonpointer - JSON Pointer (RFC 6901)
Compound Types
  • object - Object with typed properties
  • array - Homogeneous array
  • set - Array with unique items
  • map - Key-value pairs
  • tuple - Fixed-length heterogeneous array
  • choice - Union type (matches one of several schemas)
  • any - Any JSON value

Constraints

String Constraints
  • minLength - Minimum string length
  • maxLength - Maximum string length
  • pattern - Regex pattern to match
Numeric Constraints
  • minimum - Minimum value (inclusive)
  • maximum - Maximum value (inclusive)
  • exclusiveMinimum - Minimum value (exclusive)
  • exclusiveMaximum - Maximum value (exclusive)
  • multipleOf - Value must be a multiple of this
Array/Set Constraints
  • minItems - Minimum number of items
  • maxItems - Maximum number of items
  • uniqueItems - Whether items must be unique (implicit for set)
Object Constraints
  • required - Required property names
  • additionalProperties - Allow additional properties
General Constraints
  • enum - Allowed values
  • const - Single allowed value

Schema Composition

  • allOf - Must match all schemas
  • anyOf - Must match at least one schema
  • oneOf - Must match exactly one schema
  • not - Must not match schema
  • if/then/else - Conditional validation

References

  • $ref - Reference to another schema (JSON Pointer)
  • definitions - Schema definitions (type namespace hierarchy)

Development

Running Tests
go test ./...
Running Tests with Coverage
go test -cover ./...

License

MIT License - see LICENSE for details.

Documentation

Overview

Package jsonstructure provides validators for JSON Structure schemas and instances.

JSON Structure is a type system for JSON that provides precise data typing with support for numeric types (int8, int16, int32, int64, uint8, uint16, uint32, uint64, float8, float, double, decimal, integer), temporal types (datetime, date, time, duration), and structured types (object, array, tuple, map, set, choice).

Schema Validation

Use SchemaValidator to validate JSON Structure schema documents:

validator := jsonstructure.NewSchemaValidator(nil)
result := validator.Validate(schemaMap)
if result.Valid {
    // Schema is valid
}

Instance Validation

Use InstanceValidator to validate JSON instances against schemas:

validator := jsonstructure.NewInstanceValidator(nil)
result := validator.Validate(instance, schema)
if result.Valid {
    // Instance conforms to schema
}

Serialization

The package provides JSON marshaling/unmarshaling that preserves precision for large integers by serializing them as strings:

data := jsonstructure.LargeIntData{Value: "9223372036854775807"}
jsonBytes, _ := json.Marshal(data)

For more information, see https://json-structure.org

Package jsonstructure provides validators for JSON Structure schemas and instances.

Package jsonstructure provides validators for JSON Structure schemas and instances.

Package jsonstructure provides validators for JSON Structure schemas and instances.

Package jsonstructure provides validators for JSON Structure schemas and instances.

Package jsonstructure provides validators for JSON Structure schemas and instances.

Index

Constants

View Source
const (
	// SchemaError is a generic schema error.
	SchemaError = "SCHEMA_ERROR"
	// SchemaNull indicates schema cannot be null.
	SchemaNull = "SCHEMA_NULL"
	// SchemaInvalidType indicates schema must be a boolean or object.
	SchemaInvalidType = "SCHEMA_INVALID_TYPE"
	// SchemaMaxDepthExceeded indicates maximum validation depth exceeded.
	SchemaMaxDepthExceeded = "SCHEMA_MAX_DEPTH_EXCEEDED"
	// SchemaKeywordInvalidType indicates keyword has invalid type.
	SchemaKeywordInvalidType = "SCHEMA_KEYWORD_INVALID_TYPE"
	// SchemaKeywordEmpty indicates keyword cannot be empty.
	SchemaKeywordEmpty = "SCHEMA_KEYWORD_EMPTY"
	// SchemaTypeInvalid indicates invalid type name.
	SchemaTypeInvalid = "SCHEMA_TYPE_INVALID"
	// SchemaTypeArrayEmpty indicates type array cannot be empty.
	SchemaTypeArrayEmpty = "SCHEMA_TYPE_ARRAY_EMPTY"
	// SchemaTypeObjectMissingRef indicates type object must contain $ref.
	SchemaTypeObjectMissingRef = "SCHEMA_TYPE_OBJECT_MISSING_REF"
	// SchemaRefNotFound indicates $ref target does not exist.
	SchemaRefNotFound = "SCHEMA_REF_NOT_FOUND"
	// SchemaRefCircular indicates circular reference detected.
	SchemaRefCircular = "SCHEMA_REF_CIRCULAR"
	// SchemaExtendsCircular indicates circular $extends reference detected.
	SchemaExtendsCircular = "SCHEMA_EXTENDS_CIRCULAR"
	// SchemaExtendsNotFound indicates $extends reference not found.
	SchemaExtendsNotFound = "SCHEMA_EXTENDS_NOT_FOUND"
	// SchemaRefNotInType indicates $ref is only permitted inside the 'type' attribute.
	SchemaRefNotInType = "SCHEMA_REF_NOT_IN_TYPE"
	// SchemaMissingType indicates schema must have a 'type' keyword.
	SchemaMissingType = "SCHEMA_MISSING_TYPE"
	// SchemaRootMissingType indicates root schema must have 'type', '$root', or other schema-defining keyword.
	SchemaRootMissingType = "SCHEMA_ROOT_MISSING_TYPE"
	// SchemaRootMissingID indicates root schema must have an '$id' keyword.
	SchemaRootMissingID = "SCHEMA_ROOT_MISSING_ID"
	// SchemaRootMissingName indicates root schema with 'type' must have a 'name' property.
	SchemaRootMissingName = "SCHEMA_ROOT_MISSING_NAME"
	// SchemaExtensionKeywordNotEnabled indicates validation extension keyword is used but validation extensions are not enabled.
	SchemaExtensionKeywordNotEnabled = "SCHEMA_EXTENSION_KEYWORD_NOT_ENABLED"
	// SchemaNameInvalid indicates name is not a valid identifier.
	SchemaNameInvalid = "SCHEMA_NAME_INVALID"
	// SchemaConstraintInvalidForType indicates constraint is not valid for this type.
	SchemaConstraintInvalidForType = "SCHEMA_CONSTRAINT_INVALID_FOR_TYPE"
	// SchemaMinGreaterThanMax indicates minimum cannot be greater than maximum.
	SchemaMinGreaterThanMax = "SCHEMA_MIN_GREATER_THAN_MAX"
	// SchemaPropertiesNotObject indicates properties must be an object.
	SchemaPropertiesNotObject = "SCHEMA_PROPERTIES_NOT_OBJECT"
	// SchemaRequiredNotArray indicates required must be an array.
	SchemaRequiredNotArray = "SCHEMA_REQUIRED_NOT_ARRAY"
	// SchemaRequiredItemNotString indicates required array items must be strings.
	SchemaRequiredItemNotString = "SCHEMA_REQUIRED_ITEM_NOT_STRING"
	// SchemaRequiredPropertyNotDefined indicates required property is not defined in properties.
	SchemaRequiredPropertyNotDefined = "SCHEMA_REQUIRED_PROPERTY_NOT_DEFINED"
	// SchemaAdditionalPropertiesInvalid indicates additionalProperties must be a boolean or schema.
	SchemaAdditionalPropertiesInvalid = "SCHEMA_ADDITIONAL_PROPERTIES_INVALID"
	// SchemaArrayMissingItems indicates array type requires 'items' or 'contains' schema.
	SchemaArrayMissingItems = "SCHEMA_ARRAY_MISSING_ITEMS"
	// SchemaTupleMissingDefinition indicates tuple type requires 'properties' and 'tuple' keyword.
	SchemaTupleMissingDefinition = "SCHEMA_TUPLE_MISSING_DEFINITION"
	// SchemaTupleOrderNotArray indicates tuple must be an array.
	SchemaTupleOrderNotArray = "SCHEMA_TUPLE_ORDER_NOT_ARRAY"
	// SchemaMapMissingValues indicates map type requires 'values' schema.
	SchemaMapMissingValues = "SCHEMA_MAP_MISSING_VALUES"
	// SchemaChoiceMissingChoices indicates choice type requires 'choices' keyword.
	SchemaChoiceMissingChoices = "SCHEMA_CHOICE_MISSING_CHOICES"
	// SchemaChoicesNotObject indicates choices must be an object.
	SchemaChoicesNotObject = "SCHEMA_CHOICES_NOT_OBJECT"
	// SchemaPatternInvalid indicates pattern is not a valid regular expression.
	SchemaPatternInvalid = "SCHEMA_PATTERN_INVALID"
	// SchemaPatternNotString indicates pattern must be a string.
	SchemaPatternNotString = "SCHEMA_PATTERN_NOT_STRING"
	// SchemaEnumNotArray indicates enum must be an array.
	SchemaEnumNotArray = "SCHEMA_ENUM_NOT_ARRAY"
	// SchemaEnumEmpty indicates enum array cannot be empty.
	SchemaEnumEmpty = "SCHEMA_ENUM_EMPTY"
	// SchemaEnumDuplicates indicates enum array contains duplicate values.
	SchemaEnumDuplicates = "SCHEMA_ENUM_DUPLICATES"
	// SchemaCompositionEmpty indicates composition keyword array cannot be empty.
	SchemaCompositionEmpty = "SCHEMA_COMPOSITION_EMPTY"
	// SchemaCompositionNotArray indicates composition keyword must be an array.
	SchemaCompositionNotArray = "SCHEMA_COMPOSITION_NOT_ARRAY"
	// SchemaAltnamesNotObject indicates altnames must be an object.
	SchemaAltnamesNotObject = "SCHEMA_ALTNAMES_NOT_OBJECT"
	// SchemaAltnamesValueNotString indicates altnames values must be strings.
	SchemaAltnamesValueNotString = "SCHEMA_ALTNAMES_VALUE_NOT_STRING"
	// SchemaIntegerConstraintInvalid indicates keyword must be a non-negative integer.
	SchemaIntegerConstraintInvalid = "SCHEMA_INTEGER_CONSTRAINT_INVALID"
	// SchemaNumberConstraintInvalid indicates keyword must be a number.
	SchemaNumberConstraintInvalid = "SCHEMA_NUMBER_CONSTRAINT_INVALID"
	// SchemaPositiveNumberConstraintInvalid indicates keyword must be a positive number.
	SchemaPositiveNumberConstraintInvalid = "SCHEMA_POSITIVE_NUMBER_CONSTRAINT_INVALID"
	// SchemaUniqueItemsNotBoolean indicates uniqueItems must be a boolean.
	SchemaUniqueItemsNotBoolean = "SCHEMA_UNIQUE_ITEMS_NOT_BOOLEAN"
	// SchemaItemsInvalidForTuple indicates items must be a boolean or schema for tuple type.
	SchemaItemsInvalidForTuple = "SCHEMA_ITEMS_INVALID_FOR_TUPLE"
)
View Source
const (
	// InstanceRootUnresolved indicates unable to resolve $root reference.
	InstanceRootUnresolved = "INSTANCE_ROOT_UNRESOLVED"
	// InstanceMaxDepthExceeded indicates maximum validation depth exceeded.
	InstanceMaxDepthExceeded = "INSTANCE_MAX_DEPTH_EXCEEDED"
	// InstanceSchemaFalse indicates schema 'false' rejects all values.
	InstanceSchemaFalse = "INSTANCE_SCHEMA_FALSE"
	// InstanceRefUnresolved indicates unable to resolve reference.
	InstanceRefUnresolved = "INSTANCE_REF_UNRESOLVED"
	// InstanceConstMismatch indicates value must equal const value.
	InstanceConstMismatch = "INSTANCE_CONST_MISMATCH"
	// InstanceEnumMismatch indicates value must be one of the enum values.
	InstanceEnumMismatch = "INSTANCE_ENUM_MISMATCH"
	// InstanceAnyOfNoneMatched indicates value must match at least one schema in anyOf.
	InstanceAnyOfNoneMatched = "INSTANCE_ANY_OF_NONE_MATCHED"
	// InstanceOneOfInvalidCount indicates value must match exactly one schema in oneOf.
	InstanceOneOfInvalidCount = "INSTANCE_ONE_OF_INVALID_COUNT"
	// InstanceNotMatched indicates value must not match the schema in 'not'.
	InstanceNotMatched = "INSTANCE_NOT_MATCHED"
	// InstanceTypeUnknown indicates unknown type.
	InstanceTypeUnknown = "INSTANCE_TYPE_UNKNOWN"
	// InstanceTypeMismatch indicates type mismatch.
	InstanceTypeMismatch = "INSTANCE_TYPE_MISMATCH"
	// InstanceNullExpected indicates value must be null.
	InstanceNullExpected = "INSTANCE_NULL_EXPECTED"
	// InstanceBooleanExpected indicates value must be a boolean.
	InstanceBooleanExpected = "INSTANCE_BOOLEAN_EXPECTED"
	// InstanceStringExpected indicates value must be a string.
	InstanceStringExpected = "INSTANCE_STRING_EXPECTED"
	// InstanceStringMinLength indicates string length is less than minimum.
	InstanceStringMinLength = "INSTANCE_STRING_MIN_LENGTH"
	// InstanceStringMaxLength indicates string length exceeds maximum.
	InstanceStringMaxLength = "INSTANCE_STRING_MAX_LENGTH"
	// InstanceStringPatternMismatch indicates string does not match pattern.
	InstanceStringPatternMismatch = "INSTANCE_STRING_PATTERN_MISMATCH"
	// InstancePatternInvalid indicates invalid regex pattern.
	InstancePatternInvalid = "INSTANCE_PATTERN_INVALID"
	// InstanceFormatEmailInvalid indicates string is not a valid email address.
	InstanceFormatEmailInvalid = "INSTANCE_FORMAT_EMAIL_INVALID"
	// InstanceFormatURIInvalid indicates string is not a valid URI.
	InstanceFormatURIInvalid = "INSTANCE_FORMAT_URI_INVALID"
	// InstanceFormatURIReferenceInvalid indicates string is not a valid URI reference.
	InstanceFormatURIReferenceInvalid = "INSTANCE_FORMAT_URI_REFERENCE_INVALID"
	// InstanceFormatDateInvalid indicates string is not a valid date.
	InstanceFormatDateInvalid = "INSTANCE_FORMAT_DATE_INVALID"
	// InstanceFormatTimeInvalid indicates string is not a valid time.
	InstanceFormatTimeInvalid = "INSTANCE_FORMAT_TIME_INVALID"
	// InstanceFormatDatetimeInvalid indicates string is not a valid date-time.
	InstanceFormatDatetimeInvalid = "INSTANCE_FORMAT_DATETIME_INVALID"
	// InstanceFormatUUIDInvalid indicates string is not a valid UUID.
	InstanceFormatUUIDInvalid = "INSTANCE_FORMAT_UUID_INVALID"
	// InstanceFormatIPv4Invalid indicates string is not a valid IPv4 address.
	InstanceFormatIPv4Invalid = "INSTANCE_FORMAT_IPV4_INVALID"
	// InstanceFormatIPv6Invalid indicates string is not a valid IPv6 address.
	InstanceFormatIPv6Invalid = "INSTANCE_FORMAT_IPV6_INVALID"
	// InstanceFormatHostnameInvalid indicates string is not a valid hostname.
	InstanceFormatHostnameInvalid = "INSTANCE_FORMAT_HOSTNAME_INVALID"
	// InstanceNumberExpected indicates value must be a number.
	InstanceNumberExpected = "INSTANCE_NUMBER_EXPECTED"
	// InstanceIntegerExpected indicates value must be an integer.
	InstanceIntegerExpected = "INSTANCE_INTEGER_EXPECTED"
	// InstanceIntRangeInvalid indicates integer value is out of range.
	InstanceIntRangeInvalid = "INSTANCE_INT_RANGE_INVALID"
	// InstanceNumberMinimum indicates value is less than minimum.
	InstanceNumberMinimum = "INSTANCE_NUMBER_MINIMUM"
	// InstanceNumberMaximum indicates value exceeds maximum.
	InstanceNumberMaximum = "INSTANCE_NUMBER_MAXIMUM"
	// InstanceNumberExclusiveMinimum indicates value must be greater than exclusive minimum.
	InstanceNumberExclusiveMinimum = "INSTANCE_NUMBER_EXCLUSIVE_MINIMUM"
	// InstanceNumberExclusiveMaximum indicates value must be less than exclusive maximum.
	InstanceNumberExclusiveMaximum = "INSTANCE_NUMBER_EXCLUSIVE_MAXIMUM"
	// InstanceNumberMultipleOf indicates value is not a multiple of the specified value.
	InstanceNumberMultipleOf = "INSTANCE_NUMBER_MULTIPLE_OF"
	// InstanceObjectExpected indicates value must be an object.
	InstanceObjectExpected = "INSTANCE_OBJECT_EXPECTED"
	// InstanceRequiredPropertyMissing indicates missing required property.
	InstanceRequiredPropertyMissing = "INSTANCE_REQUIRED_PROPERTY_MISSING"
	// InstanceAdditionalPropertyNotAllowed indicates additional property not allowed.
	InstanceAdditionalPropertyNotAllowed = "INSTANCE_ADDITIONAL_PROPERTY_NOT_ALLOWED"
	// InstanceMinProperties indicates object has fewer properties than minimum.
	InstanceMinProperties = "INSTANCE_MIN_PROPERTIES"
	// InstanceMaxProperties indicates object has more properties than maximum.
	InstanceMaxProperties = "INSTANCE_MAX_PROPERTIES"
	// InstanceDependentRequired indicates dependent required property is missing.
	InstanceDependentRequired = "INSTANCE_DEPENDENT_REQUIRED"
	// InstanceArrayExpected indicates value must be an array.
	InstanceArrayExpected = "INSTANCE_ARRAY_EXPECTED"
	// InstanceMinItems indicates array has fewer items than minimum.
	InstanceMinItems = "INSTANCE_MIN_ITEMS"
	// InstanceMaxItems indicates array has more items than maximum.
	InstanceMaxItems = "INSTANCE_MAX_ITEMS"
	// InstanceMinContains indicates array has fewer matching items than minContains.
	InstanceMinContains = "INSTANCE_MIN_CONTAINS"
	// InstanceMaxContains indicates array has more matching items than maxContains.
	InstanceMaxContains = "INSTANCE_MAX_CONTAINS"
	// InstanceSetExpected indicates value must be an array (set).
	InstanceSetExpected = "INSTANCE_SET_EXPECTED"
	// InstanceSetDuplicate indicates set contains duplicate value.
	InstanceSetDuplicate = "INSTANCE_SET_DUPLICATE"
	// InstanceMapExpected indicates value must be an object (map).
	InstanceMapExpected = "INSTANCE_MAP_EXPECTED"
	// InstanceMapMinEntries indicates map has fewer entries than minimum.
	InstanceMapMinEntries = "INSTANCE_MAP_MIN_ENTRIES"
	// InstanceMapMaxEntries indicates map has more entries than maximum.
	InstanceMapMaxEntries = "INSTANCE_MAP_MAX_ENTRIES"
	// InstanceMapKeyInvalid indicates map key does not match keyNames or patternKeys constraint.
	InstanceMapKeyInvalid = "INSTANCE_MAP_KEY_INVALID"
	// InstanceTupleExpected indicates value must be an array (tuple).
	InstanceTupleExpected = "INSTANCE_TUPLE_EXPECTED"
	// InstanceTupleLengthMismatch indicates tuple length does not match schema.
	InstanceTupleLengthMismatch = "INSTANCE_TUPLE_LENGTH_MISMATCH"
	// InstanceTupleAdditionalItems indicates tuple has additional items not defined in schema.
	InstanceTupleAdditionalItems = "INSTANCE_TUPLE_ADDITIONAL_ITEMS"
	// InstanceChoiceExpected indicates value must be an object (choice).
	InstanceChoiceExpected = "INSTANCE_CHOICE_EXPECTED"
	// InstanceChoiceMissingChoices indicates choice schema is missing choices.
	InstanceChoiceMissingChoices = "INSTANCE_CHOICE_MISSING_CHOICES"
	// InstanceChoiceSelectorMissing indicates choice selector property is missing.
	InstanceChoiceSelectorMissing = "INSTANCE_CHOICE_SELECTOR_MISSING"
	// InstanceChoiceSelectorNotString indicates selector value must be a string.
	InstanceChoiceSelectorNotString = "INSTANCE_CHOICE_SELECTOR_NOT_STRING"
	// InstanceChoiceUnknown indicates unknown choice.
	InstanceChoiceUnknown = "INSTANCE_CHOICE_UNKNOWN"
	// InstanceChoiceNoMatch indicates value does not match any choice option.
	InstanceChoiceNoMatch = "INSTANCE_CHOICE_NO_MATCH"
	// InstanceChoiceMultipleMatches indicates value matches multiple choice options.
	InstanceChoiceMultipleMatches = "INSTANCE_CHOICE_MULTIPLE_MATCHES"
	// InstanceDateExpected indicates date must be a string.
	InstanceDateExpected = "INSTANCE_DATE_EXPECTED"
	// InstanceDateFormatInvalid indicates invalid date format.
	InstanceDateFormatInvalid = "INSTANCE_DATE_FORMAT_INVALID"
	// InstanceTimeExpected indicates time must be a string.
	InstanceTimeExpected = "INSTANCE_TIME_EXPECTED"
	// InstanceTimeFormatInvalid indicates invalid time format.
	InstanceTimeFormatInvalid = "INSTANCE_TIME_FORMAT_INVALID"
	// InstanceDatetimeExpected indicates datetime must be a string.
	InstanceDatetimeExpected = "INSTANCE_DATETIME_EXPECTED"
	// InstanceDatetimeFormatInvalid indicates invalid datetime format.
	InstanceDatetimeFormatInvalid = "INSTANCE_DATETIME_FORMAT_INVALID"
	// InstanceDurationExpected indicates duration must be a string.
	InstanceDurationExpected = "INSTANCE_DURATION_EXPECTED"
	// InstanceDurationFormatInvalid indicates invalid duration format.
	InstanceDurationFormatInvalid = "INSTANCE_DURATION_FORMAT_INVALID"
	// InstanceUUIDExpected indicates UUID must be a string.
	InstanceUUIDExpected = "INSTANCE_UUID_EXPECTED"
	// InstanceUUIDFormatInvalid indicates invalid UUID format.
	InstanceUUIDFormatInvalid = "INSTANCE_UUID_FORMAT_INVALID"
	// InstanceURIExpected indicates URI must be a string.
	InstanceURIExpected = "INSTANCE_URI_EXPECTED"
	// InstanceURIFormatInvalid indicates invalid URI format.
	InstanceURIFormatInvalid = "INSTANCE_URI_FORMAT_INVALID"
	// InstanceURIMissingScheme indicates URI must have a scheme.
	InstanceURIMissingScheme = "INSTANCE_URI_MISSING_SCHEME"
	// InstanceBinaryExpected indicates binary must be a base64 string.
	InstanceBinaryExpected = "INSTANCE_BINARY_EXPECTED"
	// InstanceBinaryEncodingInvalid indicates invalid base64 encoding.
	InstanceBinaryEncodingInvalid = "INSTANCE_BINARY_ENCODING_INVALID"
	// InstanceJSONPointerExpected indicates JSON Pointer must be a string.
	InstanceJSONPointerExpected = "INSTANCE_JSONPOINTER_EXPECTED"
	// InstanceJSONPointerFormatInvalid indicates invalid JSON Pointer format.
	InstanceJSONPointerFormatInvalid = "INSTANCE_JSONPOINTER_FORMAT_INVALID"
	// InstanceDecimalExpected indicates value must be a valid decimal.
	InstanceDecimalExpected = "INSTANCE_DECIMAL_EXPECTED"
	// InstanceStringNotExpected indicates string value not expected for this type.
	InstanceStringNotExpected = "INSTANCE_STRING_NOT_EXPECTED"
	// InstanceCustomTypeNotSupported indicates custom type reference not yet supported.
	InstanceCustomTypeNotSupported = "INSTANCE_CUSTOM_TYPE_NOT_SUPPORTED"
)

Variables

AllTypes lists all valid JSON Structure types.

View Source
var CompoundTypes = []string{
	"object", "array", "set", "map", "tuple", "choice", "any",
}

CompoundTypes lists all compound types supported by JSON Structure Core.

View Source
var NumericTypes = []string{
	"number", "integer", "float", "double", "decimal", "float8",
	"int8", "uint8", "int16", "uint16", "int32", "uint32",
	"int64", "uint64", "int128", "uint128",
}

NumericTypes lists all numeric types.

View Source
var PrimitiveTypes = []string{
	"string", "boolean", "null",
	"int8", "uint8", "int16", "uint16", "int32", "uint32",
	"int64", "uint64", "int128", "uint128",
	"float", "float8", "double", "decimal",
	"number", "integer",
	"date", "datetime", "time", "duration",
	"uuid", "uri", "binary", "jsonpointer",
}

PrimitiveTypes lists all primitive types supported by JSON Structure Core.

Functions

func FormatDuration

func FormatDuration(d time.Duration) string

FormatDuration formats a time.Duration as an ISO 8601 duration string.

func ParseDuration

func ParseDuration(s string) (time.Duration, error)

ParseDuration parses an ISO 8601 duration string to time.Duration.

Types

type BigIntString

type BigIntString struct {
	*big.Int
}

BigIntString is a wrapper for *big.Int that serializes to/from a JSON string. Use this for JSON Structure int128/uint128 fields.

func NewBigIntString

func NewBigIntString(v int64) BigIntString

NewBigIntString creates a new BigIntString from an int64.

func NewBigIntStringFromString

func NewBigIntStringFromString(s string) (BigIntString, error)

NewBigIntStringFromString creates a new BigIntString from a string.

func (BigIntString) MarshalJSON

func (b BigIntString) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*BigIntString) UnmarshalJSON

func (b *BigIntString) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Binary

type Binary []byte

Binary represents binary data that serializes as base64.

func (Binary) MarshalJSON

func (b Binary) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Binary) UnmarshalJSON

func (b *Binary) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Date

type Date struct {
	Year  int
	Month time.Month
	Day   int
}

Date represents a date without time (JSON Structure "date" type). Serializes as RFC 3339 date string (YYYY-MM-DD).

func NewDate

func NewDate(year int, month time.Month, day int) Date

NewDate creates a Date from year, month, day.

func NewDateFromTime

func NewDateFromTime(t time.Time) Date

NewDateFromTime creates a Date from a time.Time.

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Date) String

func (d Date) String() string

String returns the date in RFC 3339 format.

func (Date) Time

func (d Date) Time() time.Time

Time returns the Date as a time.Time at midnight UTC.

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type DateTime

type DateTime time.Time

DateTime is an alias for time.Time with RFC 3339 serialization. This is already the default behavior of time.Time in encoding/json, but this type makes the intent explicit.

func (DateTime) MarshalJSON

func (dt DateTime) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (DateTime) Time

func (dt DateTime) Time() time.Time

Time returns the underlying time.Time.

func (*DateTime) UnmarshalJSON

func (dt *DateTime) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type DecimalString

type DecimalString struct {
	Value string
}

DecimalString is a wrapper for decimal values serialized as strings. For full decimal support, consider using a library like shopspring/decimal. This basic implementation uses float64 with string serialization.

func NewDecimalString

func NewDecimalString(v float64) DecimalString

NewDecimalString creates a DecimalString from a float64.

func NewDecimalStringFromString

func NewDecimalStringFromString(s string) DecimalString

NewDecimalStringFromString creates a DecimalString from a string.

func (DecimalString) Float64

func (d DecimalString) Float64() (float64, error)

Float64 returns the decimal as a float64 (may lose precision).

func (DecimalString) MarshalJSON

func (d DecimalString) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*DecimalString) UnmarshalJSON

func (d *DecimalString) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type Duration

type Duration time.Duration

Duration is a wrapper for time.Duration that serializes to/from ISO 8601 duration strings. Format examples: "PT1H30M", "P1DT12H", "PT0.5S"

func (Duration) MarshalJSON

func (d Duration) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Duration) UnmarshalJSON

func (d *Duration) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (Duration) Value

func (d Duration) Value() time.Duration

Value returns the underlying time.Duration.

type InstanceValidator

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

InstanceValidator validates JSON instances against JSON Structure schemas. It is safe for concurrent use from multiple goroutines after construction.

func NewInstanceValidator

func NewInstanceValidator(options *InstanceValidatorOptions) *InstanceValidator

NewInstanceValidator creates a new InstanceValidator with the given options. The returned validator is safe for concurrent use from multiple goroutines.

func (*InstanceValidator) Validate

func (v *InstanceValidator) Validate(instance interface{}, schema interface{}) ValidationResult

Validate validates a JSON instance against a JSON Structure schema. This method is safe to call concurrently from multiple goroutines.

func (*InstanceValidator) ValidateJSON

func (v *InstanceValidator) ValidateJSON(instanceData, schemaData []byte) (ValidationResult, error)

ValidateJSON validates a JSON instance from JSON bytes against a schema. This method is safe to call concurrently from multiple goroutines.

type InstanceValidatorOptions

type InstanceValidatorOptions struct {
	// Extended enables extended validation features (minLength, pattern, etc.).
	Extended bool
	// AllowImport enables processing of $import/$importdefs.
	AllowImport bool
	// MaxValidationDepth is the maximum depth for validation recursion. Default is 64.
	MaxValidationDepth int
}

InstanceValidatorOptions configures instance validation.

type Int64String

type Int64String int64

Int64String is a wrapper for int64 that serializes to/from a JSON string. Use this for JSON Structure int64 fields to preserve precision.

func (Int64String) MarshalJSON

func (i Int64String) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Int64String) UnmarshalJSON

func (i *Int64String) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (Int64String) Value

func (i Int64String) Value() int64

Value returns the underlying int64 value.

type JSONPointer

type JSONPointer string

JSONPointer represents a JSON Pointer (RFC 6901) as a string.

func (JSONPointer) MarshalJSON

func (p JSONPointer) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (JSONPointer) String

func (p JSONPointer) String() string

String returns the JSON Pointer as a string.

func (*JSONPointer) UnmarshalJSON

func (p *JSONPointer) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type JsonLocation

type JsonLocation struct {
	// Line is the 1-based line number.
	Line int `json:"line"`
	// Column is the 1-based column number.
	Column int `json:"column"`
}

JsonLocation represents a location in a JSON document with line and column information.

func UnknownLocation

func UnknownLocation() JsonLocation

UnknownLocation returns an unknown location (line 0, column 0).

func (JsonLocation) IsKnown

func (l JsonLocation) IsKnown() bool

IsKnown returns true if the location is known (non-zero).

type JsonSourceLocator

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

JsonSourceLocator tracks line and column positions in a JSON document and maps JSON Pointer paths to source locations.

func NewJsonSourceLocator

func NewJsonSourceLocator(jsonText string) *JsonSourceLocator

NewJsonSourceLocator creates a new source locator for the given JSON text.

func (*JsonSourceLocator) GetLocation

func (l *JsonSourceLocator) GetLocation(path string) JsonLocation

GetLocation returns the source location for a JSON Pointer path.

type SchemaValidator

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

SchemaValidator validates JSON Structure schema documents. It is safe for concurrent use from multiple goroutines after construction.

func NewSchemaValidator

func NewSchemaValidator(options *SchemaValidatorOptions) *SchemaValidator

NewSchemaValidator creates a new SchemaValidator with the given options. The returned validator is safe for concurrent use from multiple goroutines.

func (*SchemaValidator) Validate

func (v *SchemaValidator) Validate(schema interface{}) ValidationResult

Validate validates a JSON Structure schema document. This method is safe to call concurrently from multiple goroutines.

func (*SchemaValidator) ValidateJSON

func (v *SchemaValidator) ValidateJSON(jsonData []byte) (ValidationResult, error)

ValidateJSON validates a JSON Structure schema from JSON bytes. This method is safe to call concurrently from multiple goroutines.

type SchemaValidatorOptions

type SchemaValidatorOptions struct {
	// Extended enables extended validation features.
	Extended bool
	// AllowDollar allows $ in property names (required for validating metaschemas).
	AllowDollar bool
	// AllowImport enables processing of $import/$importdefs.
	AllowImport bool
	// ExternalSchemas maps URIs to schema objects for import resolution.
	// Each schema should have a '$id' field matching the import URI.
	ExternalSchemas map[string]interface{}
	// MaxValidationDepth is the maximum depth for validation recursion. Default is 64.
	MaxValidationDepth int
	// WarnOnUnusedExtensionKeywords controls whether to emit warnings when extension
	// keywords are used without being enabled via $schema or $uses. Default is true.
	WarnOnUnusedExtensionKeywords *bool
}

SchemaValidatorOptions configures schema validation.

type TimeOfDay

type TimeOfDay struct {
	Hour       int
	Minute     int
	Second     int
	Nanosecond int
}

TimeOfDay represents a time without date (JSON Structure "time" type). Serializes as RFC 3339 time string (HH:MM:SS or HH:MM:SS.sss).

func NewTimeOfDay

func NewTimeOfDay(hour, minute, second int) TimeOfDay

NewTimeOfDay creates a TimeOfDay from hour, minute, second.

func NewTimeOfDayFromTime

func NewTimeOfDayFromTime(t time.Time) TimeOfDay

NewTimeOfDayFromTime creates a TimeOfDay from a time.Time.

func (TimeOfDay) MarshalJSON

func (t TimeOfDay) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (TimeOfDay) String

func (t TimeOfDay) String() string

String returns the time in RFC 3339 format.

func (*TimeOfDay) UnmarshalJSON

func (t *TimeOfDay) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type UInt64String

type UInt64String uint64

UInt64String is a wrapper for uint64 that serializes to/from a JSON string. Use this for JSON Structure uint64 fields to preserve precision.

func (UInt64String) MarshalJSON

func (u UInt64String) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*UInt64String) UnmarshalJSON

func (u *UInt64String) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

func (UInt64String) Value

func (u UInt64String) Value() uint64

Value returns the underlying uint64 value.

type URI

type URI struct {
	*url.URL
}

URI represents a URI that serializes as a string.

func NewURI

func NewURI(s string) (URI, error)

NewURI creates a URI from a string.

func (URI) MarshalJSON

func (u URI) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*URI) UnmarshalJSON

func (u *URI) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type UUID

type UUID string

UUID represents a UUID that serializes as a string. This is a simple string wrapper - for full UUID support, consider using a library like google/uuid.

func (UUID) MarshalJSON

func (u UUID) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (UUID) String

func (u UUID) String() string

String returns the UUID as a string.

func (*UUID) UnmarshalJSON

func (u *UUID) UnmarshalJSON(data []byte) error

UnmarshalJSON implements json.Unmarshaler.

type ValidationError

type ValidationError struct {
	// Code is the error code for programmatic handling.
	Code string `json:"code"`
	// Message is a human-readable error description.
	Message string `json:"message"`
	// Path is the JSON Pointer path to the error location.
	Path string `json:"path,omitempty"`
	// Severity is the severity of the validation message.
	Severity ValidationSeverity `json:"severity,omitempty"`
	// Location is the source location (line/column) of the error.
	Location JsonLocation `json:"location,omitempty"`
	// SchemaPath is the path in the schema that caused the error.
	SchemaPath string `json:"schemaPath,omitempty"`
}

ValidationError represents a single validation error.

func (ValidationError) String

func (e ValidationError) String() string

String returns a formatted string representation of the error.

type ValidationResult

type ValidationResult struct {
	// IsValid indicates whether the validation passed.
	IsValid bool `json:"isValid"`
	// Errors contains validation errors (empty if valid).
	Errors []ValidationError `json:"errors"`
	// Warnings contains validation warnings (non-fatal issues).
	Warnings []ValidationError `json:"warnings"`
}

ValidationResult represents the result of a validation operation.

type ValidationSeverity

type ValidationSeverity string

ValidationSeverity represents the severity of a validation message.

const (
	// SeverityError represents an error severity.
	SeverityError ValidationSeverity = "error"
	// SeverityWarning represents a warning severity.
	SeverityWarning ValidationSeverity = "warning"
)

Directories

Path Synopsis
Go SDK - Error Codes Demo
Go SDK - Error Codes Demo

Jump to

Keyboard shortcuts

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