jsonschema

package module
v0.0.0-...-46ecbf3 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2025 License: BSD-3-Clause Imports: 3 Imported by: 0

README

JSON Schema Support

This module provides JSON schema support. A JSON schema may be used to describe the structure and values that are permitted in a JSON object. These packages support creating JSON schemas by

  • unmarshaling them from a JSON object
  • building them piece by piece by calling functions
  • inferring the JSON schema for a Go struct

Given a JSON schema, you can validate whether a Go struct or a JSON object satisfies the schema.

The implementation of JSON schemas is fairly efficient both in memory space and in determining whether an instance is valid according to a schema.

JSON Schema Versions

This module currently supports JSON schema versions draft-07, draft2019-09, and draft2020-12.

The module is flexible and support for more versions can be added.

It is possible to define your own custom JSON schema keywords, although this is not well tested. Custom vocabularies are not currently supported.

Status

The current implementation and API should be considered experimental. While the basic approach and representation is unlikely to change, details may shift.

Examples

Decode JSON schema and use it to verify objects
// VerifySchema takes a JSON encoded JSON schema and
// a set of encoded JSON values.
// If the returned error satisfies jsonschema.IsValidationError
// Then the error indicates that validating against the JSON schema failed.
// Otherwise there was an error in decoding or using the JSON values.
func VerifySchema(schemaBytes io.Reader, valsBytes []io.Reader) error {
	var schema jsonschema.Schema
	if err := json.NewDecoder(schemaBytes).Decode(&schema); err != nil {
		return err
	}
	for _, valBytes := range valsBytes {
		var val any
		if err := json.NewDecoder(valBytes).Decode(&val); err != nil {
			return err
		}
		if err := schema.Validate(val); err != nil {
			return err
		}
	}
	return nil
}
Build JSON schema
// BuildPersonSchema builds a JSON schema
// that validates records with a name and an age.
// This uses the draft202012 JSON schema version;
// other schema versions would work as well.
func BuildPersonSchema() *jsonschema.Schema {
	builder := draft202012.NewBuilder()
	// Each JSON value must be an "object",
	// meaning a map from string to value.
	builder.AddType("object")
	// Describe properties of the JSON object keys.
	builder.AddProperties(map[string]*jsonschema.Schema{
		// A name must be a string.
		"name": draft202012.NewSubBuilder().
			AddType("string").
			Build(),
		// An age must be an integer between 0 and 150.
		"age": draft202012.NewSubBuilder().
			AddType("integer").
			AddMinimum(0).
			AddMaximum(150).
			Build(),
	})
	// The name and age properties must be present.
	builder.AddRequired([]string{"name", "age"})
	// No other properties may be present.
	builder.AddAdditionalProperties(draft202012.NewSubBuilder.BoolSchema(false))
	// Build and return the schema.
	return builder.Build()
}

For example, using this function like this:

var data = []map[string]any{
	map[string]any{
		"name": "me",
		"age": 10,
	},
	map[string]any{
		"age": 10,
	},
	map[string]any{
		"name": "me",
		"age": "me2",
	},
	map[string]any{
		"name": "me",
		"age": 10,
		"citizenship": "USA",
	},
}

func main() {
	s := BuildPersonSchema()
	for i, val := range data {
		fmt.Printf("%d: %v\n", i, s.Validate(val))
	}
}

will print

0: <nil>
1: required/name: missing required field "name"
2: properties/age: instance has type "string", want "integer"
3: additionalProperties/citizenship: false schema never matches
Infer JSON schema
// Person represent a person.
type Person struct {
	Name string `json:"name"`
	Age  int    `json:"age,omitempty"`
}

// PersonSchema returns a JSON schema for
// objects that will unmarshal into Person.
func PersonSchema() *jsonschema.Schema {
	builder := draft202012.NewBuilder()
	builder, err := draft202012.Infer[Person](builder, nil)
	if err != nil {
		// Everything here is completely under
		// the program's control,
		// so this should never fail.
		log.Fatal(err)
	}
	// This will return the JSON schema
	//
	//    {
	//     "$schema": "https://json-schema.org/draft/2020-12/schema",
	//     "type": "object"
	//     "properties": {
	//      "age": {
	//       "type": "integer"
	//      },
	//      "name": {
	//       "type": "string"
	//      }
	//     },
	//     "additionalProperties": false,
	//     "required": [
	//      "name"
	//     ],
	//    }
	return builder.Build()
}

Details

Annotations

The jsonschema package does not provide annotations to the calling code.

Validation errors are reported with a reference to the invalid location, but those references are not currently well defined JSON pointers.

Regular expressions

The "pattern" and "patternProperties" keywords, and the "format" keyword with "regex", use regular expressions. The JSON schema specification calls for these regular expressions to use the ECMA 262 regular expression syntax. However, the jsonschema package uses the Go regexp package syntax instead.

Format checking

The jsonschema package does not check the "format" keyword by default. Checking "format" requires both

Content type checking

The jsonschema package does not check the "contentEncoding", "contendMediaType", or "contentSchema" keywords.

Documentation

Overview

Package jsonschema implements JSON schemas.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func IsValidationError

func IsValidationError(err error) bool

IsValidationError reports whether err is a validation error. If this reports true on an error returned by [Schema.Validate], it means that the instance does not match the schema. If this reports false, it means that there is some error in the JSON schema itself.

func SetDefaultSchema

func SetDefaultSchema(s string) error

SetDefaultSchema sets the default schema. The argument should be something like "draft7" or "draft2020-12". This is a global property, as there is no way to pass the desired value into the JSON decoder. Callers should use appropriate locking. This is mainly for tests.

func SetLoader

func SetLoader(fn func(schemaID string, uri *url.URL) (*Schema, error)) func(string, *url.URL) (*Schema, error)

SetLoader sets a function to call when resolving a $ref to an external schema. This is a global property, as there is no way to pass the desired value into the JSON decoder. Callers should use appropriate locking.

Note that when unmarshaling user-written schemas, the loader function can be called with arbitrary URIs. It's probably unwise to simply call net/http.Get in all cases.

To fully support JSON schema cross references, the loader should call SchemaFromJSON. The caller will handle calling [Schema.Resolve].

This returns the old loader function. The default loader function is nil, which will produce an error for a $ref to an external schema.

Types

type ResolveOpts

type ResolveOpts = types.ResolveOpts

ResolveOpts is options that may be passed to [Schema.Resolve].

type Schema

type Schema = types.Schema

Schema is a JSON schema. A JSON schema determines whether an instance is valid or not.

If you have a JSON schema in JSON format, unmarshal it into a value of this type:

var s jsonschema.Schema
if err := json.Unmarshal(data, &s); err != nil {
	// handle error
}

To create a JSON schema in Go code, use a Builder for the schema version you want to use; do not just fill in the Parts slice. For the current default JSON schema version use [draft202012.NewBuilder].

You can also infer a JSON schema from a Go type. That is, given a Go type, you can build a JSON schema that tests that a JSON value can be unmarshaled into a value of that Go type. To do this create a Builder for the schema version you want to use, and call [builder.Infer] or [builder.InferType].

func SchemaFromJSON

func SchemaFromJSON(schemaID string, uri *url.URL, v any) (*Schema, error)

SchemaFromJSON builds a Schema from a JSON value that has already been parsed. This could be used as something like

var v any
if err := json.Unmarshal(data, &v); err != nil { ... }
s, err := schema.SchemaFromJSON(v)

This can be useful in cases where it's not clear whether the JSON encoding contains a schema or not.

The optional schemaID argument is something like [draft202012.SchemaID]. The optional uri is where the schema was loaded from.

It is normally necessary to call Resolve on the result.

type ValidateOpts

type ValidateOpts = types.ValidateOpts

ValidateOpts describes validation options that may be passed to [Schema.ValidateWithOpts]. These are uncommon so we use a different method for them.

Directories

Path Synopsis
Package builder defines a Builder type that may be used to build a [jsonschema.Schema] step by step.
Package builder defines a Builder type that may be used to build a [jsonschema.Schema] step by step.
Package draft201909 defines the keywords used by JSON schema version 2020-109.
Package draft201909 defines the keywords used by JSON schema version 2020-109.
Package draft202012 defines the keywords used by JSON schema version 2020-12.
Package draft202012 defines the keywords used by JSON schema version 2020-12.
Package draft7 defines the keywords used by JSON schema version draft7.
Package draft7 defines the keywords used by JSON schema version draft7.
Package format defines format checkers for the format keyword.
Package format defines format checkers for the format keyword.
internal
argtype
Package argtype defines a few helpers for schema.ArgType.
Package argtype defines a few helpers for schema.ArgType.
cmd/keywordgen command
keywordgen generates repetitive code for JSON schema keywords.
keywordgen generates repetitive code for JSON schema keywords.
cmd/testgen command
testgen downloads the current testsuite from json-schema-org and updates the tests in the tree.
testgen downloads the current testsuite from json-schema-org and updates the tests in the tree.
cmd/validatorgen command
validatorgen generates validator functions for different schema argument types.
validatorgen generates validator functions for different schema argument types.
schemacache
Package schemacache is a simple in-process cache for schemas that have been parsed.
Package schemacache is a simple in-process cache for schemas that have been parsed.
validator
Package validator contains functions to handle different schema arguments.
Package validator contains functions to handle different schema arguments.
validerr
Package validerr defines the errors return by a failure to validate.
Package validerr defines the errors return by a failure to validate.
Package jsonpointer implements JSON pointers for the jsonschema package.
Package jsonpointer implements JSON pointers for the jsonschema package.
Package notes defines a type that holds information passed between keywords during schema validation.
Package notes defines a type that holds information passed between keywords during schema validation.
Package types defines the JSON schema types.
Package types defines the JSON schema types.

Jump to

Keyboard shortcuts

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