jsonschema

package
v1.8.9 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: Apache-2.0 Imports: 14 Imported by: 6 modules, 5 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

jsonschema

Generates JSON Schemas from Go types, enriched with additional struct tag support. Supports structs, primitives, slices, and maps.

Usage

import "github.com/mutablelogic/go-server/pkg/jsonschema"

schema, err := jsonschema.For[MyStruct]()

For[T]() generates a schema for T, enriches it with the struct tags below, and caches the result — subsequent calls for the same type are free. T can be any Go type: a struct, string, int, bool, []string, etc.

Validation

data := json.RawMessage(`{"name":"alice","age":30}`)
if err := schema.Validate(data); err != nil {
    // err describes the validation failure
}

(*Schema).Validate(data json.RawMessage) error unmarshals the JSON and validates it against the schema. Returns nil on success. Works for all JSON types — objects, strings, numbers, booleans, and arrays.

Decode

var cfg Config
if err := schema.Decode(data, &cfg); err != nil {
    // err is a validation or unmarshal failure
}

(*Schema).Decode(data json.RawMessage, v any) error combines unmarshalling, default application, and validation in one step. Works for all JSON types:

  • Objects: applies schema defaults for any missing fields before validating, then unmarshals into v
  • Primitives and arrays: validates then unmarshals into v

Fields with a default:"" tag are automatically treated as optional so that defaults can be filled in. This can be overridden with an explicit required:"" tag.

Type mappings

Go type JSON Schema Notes
string {"type":"string"}
bool {"type":"boolean"}
int, int64, etc. {"type":"integer"}
float32, float64 {"type":"number"}
[]T {"type":"array"}
map[K]V {"type":"object"}
struct {"type":"object","properties":{…}} struct tags are applied to properties
time.Time {"type":"string","format":"date-time"} add format:"date-time" tag to advertise RFC 3339 — the format is advisory only, validation does not enforce it
time.Duration {"type":["integer","string"],"format":"duration"} integer nanoseconds, as encoding/json encodes a time.Duration, or Go duration syntax (e.g. "5s", "1h30m"); Decode parses duration strings automatically, including default:"" tags. A named duration type with its own MarshalJSON is a string
[]byte {"type":"string","format":"byte"} base64-encoded
json.RawMessage {} embedded JSON, so any JSON value, including as a map value or slice item
string + format:"uuid" tag {"type":"string","format":"uuid"} add format:"uuid" to any string or *string field — the format is advisory; validation enforces the string type only

Supported struct tags

Tag JSON Schema field Applies to Example
jsonschema:"text" description any jsonschema:"the user's name" — takes priority over help
help:"text" description any help:"the user's name" — fallback if jsonschema tag is absent
enum:"a,b,c" enum any enum:"red,green,blue" — comma-separated, values are trimmed
default:"value" default any default:"42" — type-aware: bools, ints, uints, and floats emit native JSON; time.Duration emits a duration string; all others emit a JSON string. Also removes the field from required so defaults can be applied.
format:"value" format any format:"date-time" — any valid JSON Schema format string
pattern:"regex" pattern strings pattern:"^[a-z]+"
min:"N" minimum / minLength / minItems numbers, strings, slices min:"1"
max:"N" maximum / maxLength / maxItems numbers, strings, slices max:"100"
required:"" parent required array any adds the field to the parent object's required list
optional:"" parent required array any removes the field from the parent object's required list
readonly:"" readOnly any marks the property as read-only
deprecated:"" deprecated any marks the property as deprecated
Tag precedence
  • optional takes precedence over required if both are present on the same field.
  • jsonschema takes precedence over help for descriptions.
  • A field with default:"" is implicitly optional; add required:"" to override.
Example
type Config struct {
    ID      string        `json:"id"      format:"uuid"  readonly:""   jsonschema:"resource identifier"`
    Host    string        `json:"host"    required:""   help:"Hostname or IP address"`
    Port    int           `json:"port"    default:"8080" min:"1" max:"65535"`
    Scheme  string        `json:"scheme"  enum:"http,https" default:"https"`
    Timeout time.Duration `json:"timeout" default:"30s"  help:"Request timeout"`
    Tags    []string      `json:"tags"    min:"1" max:"10"`
    Slug    string        `json:"slug"    pattern:"^[a-z0-9-]+$"`
    Key     string        `json:"key"     deprecated:"" readonly:"" help:"Use scheme instead"`
}

schema, err := jsonschema.For[Config]()

// Validate raw JSON:
if err := schema.Validate(data); err != nil { ... }

// Unmarshal + apply defaults + validate in one step:
var cfg Config
if err := schema.Decode(data, &cfg); err != nil { ... }

Produces (in part):

{
  "type": "object",
  "properties": {
    "id":      { "type": "string",  "format": "uuid", "description": "resource identifier", "readOnly": true },
    "host":    { "type": "string",  "description": "Hostname or IP address" },
    "port":    { "type": "integer", "default": 8080, "minimum": 1, "maximum": 65535 },
    "scheme":  { "type": "string",  "enum": ["http", "https"], "default": "https" },
    "timeout": { "type": "string",  "format": "duration", "default": "30s", "description": "Request timeout" },
    "tags":    { "type": "array",   "minItems": 1, "maxItems": 10 },
    "slug":    { "type": "string",  "pattern": "^[a-z0-9-]+$" },
    "key":     { "type": "string",  "description": "Use scheme instead", "readOnly": true, "deprecated": true }
  },
  "required": ["host"]
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Schema

type Schema struct {
	upstream.Schema
	// contains filtered or unexported fields
}

func For

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

For generates a JSON Schema for the given type T, enriches it with struct tag annotations, resolves any $ref references, and caches the result. Subsequent calls for the same type return the cached schema at no cost.

func FromJSON

func FromJSON(data json.RawMessage) (*Schema, error)

FromJSON parses a JSON Schema document and returns a resolved *Schema ready for use with Validate and Decode. Unlike For[T](), the result is not cached since there is no type key to cache against.

func MustFor added in v1.6.17

func MustFor[T any]() *Schema

MustFor is like For but panics if schema generation fails.

func (*Schema) Decode

func (s *Schema) Decode(data json.RawMessage, v any) error

Decode unmarshals data into v, applies schema defaults for any missing fields, then validates the result. v must be a non-nil pointer; it may point to a struct (in which case schema defaults are applied for missing fields), a primitive (string, bool, numeric), a slice, or a *time.Duration, which can be a duration string, such as "5s", or integer nanoseconds.

func (*Schema) Property added in v1.6.19

func (s *Schema) Property(name string) *Schema

Property returns the schema for the named property, or nil if the property is not present. The returned schema wraps the upstream property schema; it is not resolved and should only be used for schema generation, not for Validate or Decode.

func (*Schema) Validate

func (s *Schema) Validate(data json.RawMessage) error

Validate validates a JSON value against the schema. The data must be valid JSON. It returns nil if validation succeeds, or an error describing the failures.

Jump to

Keyboard shortcuts

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