jsonschema

package module
v0.1.11 Latest Latest
Warning

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

Go to latest
Published: Apr 5, 2021 License: MIT Imports: 6 Imported by: 0

README

Go JSON Schema Reflection

Build Status Gitter chat Go Report Card GoDoc

This package can be used to generate JSON Schemas from Go types through reflection.

  • Supports arbitrarily complex types, including interface{}, maps, slices, etc.
  • Supports json-schema features such as minLength, maxLength, pattern, format, etc.
  • Supports simple string and numeric enums.
  • Supports custom property fields via the jsonschema_extras struct tag.

Example

The following Go type:

type TestUser struct {
  ID            int                    `json:"id"`
  Name          string                 `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"`
  Friends       []int                  `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"`
  Tags          map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"`
  BirthDate     time.Time              `json:"birth_date,omitempty" jsonschema:"oneof_required=date"`
  YearOfBirth   string                 `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"`
  Metadata      interface{}            `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"`
  FavColor      string                 `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"`
}

Results in following JSON Schema:

jsonschema.Reflect(&TestUser{})
{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "$ref": "#/definitions/TestUser",
  "definitions": {
    "TestUser": {
      "type": "object",
      "properties": {
        "metadata": {
          "oneOf": [
            {
              "type": "string"
            },
            {
              "type": "array"
            }
          ]
        },
        "birth_date": {
          "type": "string",
          "format": "date-time"
        },
        "friends": {
          "type": "array",
          "items": {
            "type": "integer"
          },
          "description": "The list of IDs, omitted when empty"
        },
        "id": {
          "type": "integer"
        },
        "name": {
          "type": "string",
          "title": "the name",
          "description": "The name of a friend",
          "default": "alex",
          "examples": [
            "joe",
            "lucy"
          ]
        },
        "tags": {
          "type": "object",
          "patternProperties": {
            ".*": {
              "additionalProperties": true
            }
          },
          "a": "b",
          "foo": [
            "bar",
            "bar1"
          ]
        },
        "fav_color": {
          "type": "string",
          "enum": [
            "red",
            "green",
            "blue"
          ]
        }
      },
      "additionalProperties": false,
      "required": ["id", "name"],
      "oneOf": [
        {
          "required": [
            "birth_date"
          ],
          "title": "date"
        },
        {
          "required": [
            "year_of_birth"
          ],
          "title": "year"
        }
      ]
    }
  }
}

Configurable behaviour

The behaviour of the schema generator can be altered with parameters when a jsonschema.Reflector instance is created.

ExpandedStruct

If set to true, makes the top level struct not to reference itself in the definitions. But type passed should be a struct type.

eg.

type GrandfatherType struct {
	FamilyName string `json:"family_name" jsonschema:"required"`
}

type SomeBaseType struct {
	SomeBaseProperty int `json:"some_base_property"`
	// The jsonschema required tag is nonsensical for private and ignored properties.
	// Their presence here tests that the fields *will not* be required in the output
	// schema, even if they are tagged required.
	somePrivateBaseProperty            string `json:"i_am_private" jsonschema:"required"`
	SomeIgnoredBaseProperty            string `json:"-" jsonschema:"required"`
	SomeSchemaIgnoredProperty          string `jsonschema:"-,required"`
	SomeUntaggedBaseProperty           bool   `jsonschema:"required"`
	someUnexportedUntaggedBaseProperty bool
	Grandfather                        GrandfatherType `json:"grand"`
}

will output:

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "required": [
    "some_base_property",
    "grand",
    "SomeUntaggedBaseProperty"
  ],
  "properties": {
    "SomeUntaggedBaseProperty": {
      "type": "boolean"
    },
    "grand": {
      "$schema": "http://json-schema.org/draft-04/schema#",
      "$ref": "#/definitions/GrandfatherType"
    },
    "some_base_property": {
      "type": "integer"
    }
  },
  "type": "object",
  "definitions": {
    "GrandfatherType": {
      "required": [
        "family_name"
      ],
      "properties": {
        "family_name": {
          "type": "string"
        }
      },
      "additionalProperties": false,
      "type": "object"
    }
  }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CombineErrors

func CombineErrors(errorRange []error) error

func ItemNameFromArray

func ItemNameFromArray(array arrayType) string

ItemNameFromArray computes the supposed item name of an array

*by removing the plural 's' of the array name

func ValidateInterface

func ValidateInterface(i interfaceType) error

func ValidateStruct

func ValidateStruct(s structType) error

Types

type BasicBool

type BasicBool bool

type BasicEnum

type BasicEnum string

type BasicInt

type BasicInt int

type BasicString

type BasicString string

type Definitions

type Definitions map[string]*Type

Definitions hold schema definitions

type Reflector

type Reflector struct {
	// Use package paths as well as type names, to avoid conflicts.
	// Without this setting, if two packages contain a type with the same name,
	// and both are present in a schema, they will conflict and overwrite in
	// the definition map and produce bad output.  This is particularly
	// noticeable when using DoNotReference.
	FullyQualifyTypeNames bool
}

A Reflector reflects values into a Schema.

func (*Reflector) Reflect

func (r *Reflector) Reflect(v interface{}) (*Schema, error)

Reflect reflects to Schema from a value.

func (*Reflector) ReflectFromType

func (r *Reflector) ReflectFromType(t reflect.Type) (*Schema, error)

ReflectFromType generates root schema

type Schema

type Schema struct {
	*Type
	Definitions Definitions
}

Schema is the root schema.

func Reflect

func Reflect(v interface{}) (*Schema, error)

Reflect reflects to Schema from a value using the default Reflector

func ReflectFromType

func ReflectFromType(t reflect.Type) (*Schema, error)

ReflectFromType generates root schema using the default Reflector

func (*Schema) MarshalJSONForJS

func (s *Schema) MarshalJSONForJS(name string) ([]byte, error)

type Type

type Type struct {
	//Contained in all types
	Ref         string                 `json:"$ref,omitempty"`
	Type        string                 `json:"type,omitempty"`
	Definitions Definitions            `json:"definitions,omitempty"`
	Name        string                 `json:"name,omitempty"`
	Description string                 `json:"description,omitempty"`
	Properties  *orderedmap.OrderedMap `json:"children,omitempty"`
	Classes     []string               `json:"classes,omitempty"`
	Extras      map[string]interface{} `json:"-"`

	//exclusive for structs
	Required        []string `json:"required,omitempty"`
	InteractionText string   `json:"interactionText,omitempty"`

	//exclusive for enums
	Enum []string `json:"enum,omitempty"`

	//exclusive for strings
	Pattern string `json:"pattern,omitempty"`

	//exclusive for ints, strings, arrays
	Max int64 `json:"max,omitempty"`
	Min int64 `json:"min,omitempty"`
}

Type represents a JSON Schema object type.

func (*Type) MarshalJSON

func (t *Type) MarshalJSON() ([]byte, error)

Jump to

Keyboard shortcuts

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