jsonschema

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 28, 2026 License: Apache-2.0 Imports: 20 Imported by: 1 module, 0 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.

Documentation

Overview

Package jsonschema builds JSON Schemas (draft-07) from Go types and checks decoded YAML or JSON values against them, so editors and AI tools can complete and validate the YAML files a game's author writes.

Reflect walks a Go type the way its loader decodes it: struct fields become properties named by their yaml tags (or by Options.FieldName), structs become definitions shared through $ref, and a `schema` struct tag adds the constraints a type alone cannot say, such as `schema:"required,const=1"` or `schema:"enum=world|screen"`. Schema.Marshal writes deterministic, indented JSON, so a generated schema can be committed and checked for drift in CI, and Schema.Validate checks a value decoded from YAML or JSON against the keywords Reflect emits.

Index

Constants

View Source
const Draft07 = "http://json-schema.org/draft-07/schema#"

Draft07 is the $schema URI of the JSON Schema dialect this package writes, the newest one editors' YAML and JSON language servers support everywhere.

Variables

This section is empty.

Functions

func DecodeYAML

func DecodeYAML(data []byte) (any, error)

DecodeYAML decodes the single YAML document in data into the plain values Validate takes; empty input decodes to nil.

func PackageDocs

func PackageDocs(dir string) (map[string]string, error)

PackageDocs reads the doc comments of the Go package in dir (its non-test .go files) into the map Options.Docs takes: each type's comment under its name, and each struct field's under "Type.Field".

A field with no comment of its own takes the comment of the nearest commented field before it in the same struct when that comment names it, as in "X and Y are the world coordinates", so a pair documented together gets the same description. A comment's lines are joined into paragraphs separated by a blank line.

Types

type Field

type Field struct {
	// Name is the key the field is written under.
	Name string
	// Skip leaves the field out of the schema, as a `yaml:"-"` tag does.
	Skip bool
	// Inline merges the fields of a struct-typed field into its parent, as a `yaml:",inline"` tag does.
	Inline bool
}

Field says how a loader reads one Go struct field: the key it is written under, whether it is skipped, and whether its fields are read as if they were the parent's.

func YAMLField

func YAMLField(f reflect.StructField) Field

YAMLField maps a struct field the way go.yaml.in/yaml/v3 does: the first part of its `yaml` tag names it, "-" skips it, ",inline" merges it, and an untagged field is named by its Go name in lower case.

type Issue

type Issue struct {
	// Path is the JSON Pointer (RFC 6901) of the value within the document, "" for the document itself.
	Path string
	// Message says what is wrong with the value.
	Message string
}

Issue is one place where a value breaks its schema.

func (Issue) String

func (i Issue) String() string

String returns the issue as "<path>: <message>", with "/" standing for the document itself.

type Options

type Options struct {
	// ID is the $id URI the schema is published at; empty omits it.
	ID string
	// Title is the root schema's title; empty omits it.
	Title string
	// Description is the root schema's description; empty uses Docs for the root type.
	Description string
	// FieldName maps a struct field to the key its loader reads; nil uses YAMLField.
	FieldName func(reflect.StructField) Field
	// Docs maps a Go type's name ("SceneDoc") or a type's field ("SceneDoc.Name") to the description written for it, as PackageDocs reads them from a package's doc comments.
	Docs map[string]string
	// Types overrides the schema of a Go type wherever it appears, for types a loader reads in a form their kind does not say, such as a time.Duration written "1.5s". Each use gets its own copy.
	Types map[reflect.Type]*Schema
	// AllowUnknown leaves additionalProperties unset on struct schemas, for loaders that ignore keys they do not know; by default unknown keys are refused, as a decoder with KnownFields(true) does.
	AllowUnknown bool
	// FirstFieldWins keeps the first field written under a key and leaves out later ones, for loaders that bind each key to the first field claiming it, such as datatable's CSV and JSON loaders; by default two fields under one key are an error.
	FirstFieldWins bool
}

Options configures Reflect.

type Property

type Property struct {
	// Name is the key the property is written under.
	Name string
	// Schema constrains the property's value.
	Schema *Schema
}

Property is one named entry of an object schema's properties, kept in declaration order so a generated schema reads in the same order as the Go type.

type Schema

type Schema struct {
	// Schema is the $schema dialect URI, set on a root schema only.
	Schema string
	// ID is the $id URI a root schema is published at.
	ID string
	// Ref is a $ref to "#" or "#/definitions/<name>" in the root schema. Validate ignores the other keywords of a schema with a Ref, as draft-07 does.
	Ref string
	// Title is a short human-readable name.
	Title string
	// Description is shown by editors on hover and completion.
	Description string
	// Types lists the allowed JSON types; empty allows every type.
	Types []Type
	// Default, when non-nil, is the value a tool shows or fills in when the property is left out.
	Default any
	// Const, when non-nil, is the only allowed value.
	Const any
	// Enum, when non-empty, lists the allowed values.
	Enum []any
	// Minimum and Maximum bound a number inclusively.
	Minimum, Maximum *float64
	// ExclusiveMinimum and ExclusiveMaximum bound a number exclusively.
	ExclusiveMinimum, ExclusiveMaximum *float64
	// MinLength is the fewest characters (Unicode code points) a string may have.
	MinLength *int
	// MinItems is the fewest elements an array may have.
	MinItems *int
	// MaxItems is the most elements an array may have.
	MaxItems *int
	// Items constrains every element of an array.
	Items *Schema
	// Properties constrains an object's named properties, in declaration order.
	Properties []Property
	// Required lists the properties an object must have.
	Required []string
	// AdditionalProperties constrains the properties not named in Properties; False refuses them and nil allows any.
	AdditionalProperties *Schema
	// AllOf lists schemas a value must match all of; Reflect uses it to give a $ref a description of its own.
	AllOf []*Schema
	// Definitions holds the named subschemas that Ref points at, set on a root schema only.
	Definitions map[string]*Schema
	// contains filtered or unexported fields
}

Schema is a JSON Schema draft-07 document or subschema, limited to the keywords Reflect emits and Validate checks.

The zero Schema accepts every value; True and False return the boolean schemas.

func False

func False() *Schema

False returns the boolean schema that accepts no value; as AdditionalProperties it refuses unknown keys.

func Reflect

func Reflect(t reflect.Type, opts Options) (*Schema, error)

Reflect builds the schema of values of type t as a loader with opts reads them:

  • a struct is an object whose properties are its exported fields, named by opts.FieldName, with unknown keys refused unless opts.AllowUnknown; a struct other than the root is written once under definitions and referenced by $ref;
  • a pointer is the schema of what it points to;
  • a slice or array is an array of its elements' schema;
  • a map with string keys is an object whose values all have the map's element schema;
  • strings, booleans, integers and floats map to their JSON types, integers and float32 bounded by the range their Go type holds, and an interface accepts any value.

A field's `schema` struct tag adds what its Go type cannot say, as comma-separated entries: required, const=V, enum=A|B|C, minimum=N, maximum=N, exclusiveMinimum=N, exclusiveMaximum=N, minLength=N and minItems=N, where const and enum values are read as the field's type. Channels, functions, complex numbers and maps with keys other than strings are refused.

func True

func True() *Schema

True returns the boolean schema that accepts every value.

func (*Schema) Boolean

func (s *Schema) Boolean() (value, ok bool)

Boolean reports whether s is a boolean schema (True or False) and, if so, its value.

func (*Schema) Marshal

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

Marshal returns s as JSON indented by two spaces with a trailing newline. Keys keep a fixed order (properties in declaration order, definitions sorted by name), so the same schema always yields the same bytes.

func (*Schema) MarshalJSON

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

MarshalJSON writes s as compact JSON with the key order Marshal documents.

func (*Schema) Property

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

Property returns the schema of the named property, or nil when s has none by that name.

func (*Schema) Validate

func (s *Schema) Validate(v any) error

Validate checks v against s and returns a *ValidationError listing every issue, or nil when v conforms.

v is a value as encoding/json or ValidateYAML decodes one into an interface: nil, bool, string, a number of any Go numeric kind, []any, and map[string]any. $refs resolve against s, so call Validate on the root schema.

func (*Schema) ValidateYAML

func (s *Schema) ValidateYAML(data []byte) error

ValidateYAML decodes the single YAML document in data as a YAML language server reads it (mapping keys as strings, timestamps and binary as strings, merge keys merged, a key repeated within one mapping refused) and validates it with Validate. A document that is not YAML, or that holds more than one document, is an error that is not a *ValidationError.

type Type

type Type string

Type is a JSON Schema primitive type name.

const (
	// TypeObject is a mapping with string keys.
	TypeObject Type = "object"
	// TypeArray is a sequence.
	TypeArray Type = "array"
	// TypeString is a string.
	TypeString Type = "string"
	// TypeNumber is any number, integral or not.
	TypeNumber Type = "number"
	// TypeInteger is a number with no fractional part.
	TypeInteger Type = "integer"
	// TypeBoolean is true or false.
	TypeBoolean Type = "boolean"
	// TypeNull is null.
	TypeNull Type = "null"
)

type ValidationError

type ValidationError struct {
	// Issues holds one entry per broken keyword, never empty.
	Issues []Issue
}

ValidationError lists every place a value breaks its schema, in document order.

func (*ValidationError) Error

func (e *ValidationError) Error() string

Error returns the issues one per line.

Jump to

Keyboard shortcuts

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