jsonschema

package module
Version: v0.3.40 Latest Latest
Warning

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

Go to latest
Published: Sep 22, 2022 License: MIT Imports: 13 Imported by: 12

README

JSON Schema structures for Go

Build Status Coverage Status GoDevDoc time tracker Code lines Comments

This library provides Go structures to marshal/unmarshal and reflect JSON Schema documents.

Reflector

Documentation.

type MyStruct struct {
    Amount float64  `json:"amount" minimum:"10.5" example:"20.6" required:"true"`
    Abc    string   `json:"abc" pattern:"[abc]"`
    _      struct{} `additionalProperties:"false"`                   // Tags of unnamed field are applied to parent schema.
    _      struct{} `title:"My Struct" description:"Holds my data."` // Multiple unnamed fields can be used.
}

reflector := jsonschema.Reflector{}

schema, err := reflector.Reflect(MyStruct{})
if err != nil {
    log.Fatal(err)
}

j, err := json.MarshalIndent(schema, "", " ")
if err != nil {
    log.Fatal(err)
}

fmt.Println(string(j))

// Output:
// {
//  "title": "My Struct",
//  "description": "Holds my data.",
//  "required": [
//   "amount"
//  ],
//  "additionalProperties": false,
//  "properties": {
//   "abc": {
//    "pattern": "[abc]",
//    "type": "string"
//   },
//   "amount": {
//    "examples": [
//     20.6
//    ],
//    "minimum": 10.5,
//    "type": "number"
//   }
//  },
//  "type": "object"
// }

Customization

By default, JSON Schema is generated from Go struct field types and tags. It works well for the majority of cases, but if it does not there are rich customization options.

Field tags
type MyObj struct {
   BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
   SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
}

Note: field tags are only applied to inline schemas, if you use named type then referenced schema will be created and tags will be ignored. This happens because referenced schema can be used in multiple fields with conflicting tags, therefore customization of referenced schema has to done on the type itself via RawExposer, Exposer or Preparer.

Each tag value has to be put in double quotes ("123").

These tags can be used:

Unnamed fields can be used to configure parent schema:

type MyObj struct {
   BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
   SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
   _             struct{} `additionalProperties:"false" description:"MyObj is my object."`
}

In case of a structure with multiple name tags, you can enable filtering of unnamed fields with ReflectContext.UnnamedFieldWithTag option and add matching name tags to structure (e.g. query:"_").

type MyObj struct {
   BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
   SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
   // These parent schema tags would only be applied to `query` schema reflection (not for `json`).
   _ struct{} `query:"_" additionalProperties:"false" description:"MyObj is my object."`
}
Implementing interfaces on a type

There are a few interfaces that can be implemented on a type to customize JSON Schema generation.

And a few interfaces to expose subschemas (anyOf, allOf, oneOf, not and if, then, else).

There are also helper functions jsonschema.AllOf, jsonschema.AnyOf, jsonschema.OneOf to create exposer instance from multiple values.

Configuring the reflector

Additional centralized configuration is available with jsonschema.ReflectContext and Reflect options.

Documentation

Overview

Package jsonschema provides tools to work with JSON Schema.

Package jsonschema contains JSON mapping structures.

Index

Examples

Constants

View Source
const (
	Array   = SimpleType("array")
	Boolean = SimpleType("boolean")
	Integer = SimpleType("integer")
	Null    = SimpleType("null")
	Number  = SimpleType("number")
	Object  = SimpleType("object")
	String  = SimpleType("string")
)

SimpleType values enumeration.

View Source
const DateLayout = "2006-01-02"

DateLayout describes date format.

View Source
const (
	// ErrSkipProperty indicates that property should not be added to object.
	ErrSkipProperty = sentinelError("property skipped")
)
View Source
const (
	// XEnumNames is the name of JSON property to store names of enumerated values.
	XEnumNames = "x-enum-names"
)

Variables

This section is empty.

Functions

func CollectDefinitions added in v0.2.5

func CollectDefinitions(f func(name string, schema Schema)) func(*ReflectContext)

CollectDefinitions enables collecting definitions with provided func instead of result schema.

func DefinitionsPrefix

func DefinitionsPrefix(prefix string) func(*ReflectContext)

DefinitionsPrefix sets up location for newly created references, default "#/definitions/".

func InlineRefs

func InlineRefs(rc *ReflectContext)

InlineRefs prevents references.

func InterceptProperty

func InterceptProperty(f InterceptPropertyFunc) func(*ReflectContext)

InterceptProperty adds hook to customize property schema.

Example
reflector := jsonschema.Reflector{}

type Test struct {
	ID      int     `json:"id" minimum:"123" default:"200"`
	Name    string  `json:"name" minLength:"10"`
	Skipped float64 `json:"skipped"`
}

s, err := reflector.Reflect(new(Test),
	// PropertyNameMapping allows configuring property names without field tag.
	jsonschema.InterceptProperty(func(name string, field reflect.StructField, propertySchema *jsonschema.Schema) error {
		switch name {
		// You can alter reflected schema by updating propertySchema.
		case "id":
			propertySchema.WithDescription("This is ID.")
			// You can access schema that holds the property.
			propertySchema.Parent.WithDescription("Schema with ID.")

		// Or you can entirely remove property from parent schema with a sentinel error.
		case "skipped":
			return jsonschema.ErrSkipProperty
		}

		return nil
	}),
)
if err != nil {
	panic(err)
}

j, err := assertjson.MarshalIndentCompact(s, "", "  ", 80)
if err != nil {
	panic(err)
}

fmt.Println(string(j))
Output:

{
  "description":"Schema with ID.",
  "properties":{
    "id":{"description":"This is ID.","default":200,"minimum":123,"type":"integer"},
    "name":{"minLength":10,"type":"string"}
  },
  "type":"object"
}

func InterceptType

func InterceptType(f InterceptTypeFunc) func(*ReflectContext)

InterceptType adds hook to customize schema.

func MakePropertyNameMapping added in v0.3.8

func MakePropertyNameMapping(v interface{}, tagName string) map[string]string

MakePropertyNameMapping makes property name mapping from struct value suitable for jsonschema.PropertyNameMapping.

func ProcessWithoutTags added in v0.3.27

func ProcessWithoutTags(rc *ReflectContext)

ProcessWithoutTags enables processing fields without any tags specified.

func PropertyNameMapping added in v0.3.8

func PropertyNameMapping(mapping map[string]string) func(rc *ReflectContext)

PropertyNameMapping enables property name mapping from a struct field name.

Example
reflector := jsonschema.Reflector{}

type Test struct {
	ID   int    `minimum:"123" default:"200"`
	Name string `minLength:"10"`
}

s, err := reflector.Reflect(new(Test),
	// PropertyNameMapping allows configuring property names without field tag.
	jsonschema.PropertyNameMapping(map[string]string{
		"ID":   "ident",
		"Name": "last_name",
	}))
if err != nil {
	panic(err)
}

j, err := assertjson.MarshalIndentCompact(s, "", "  ", 80)
if err != nil {
	panic(err)
}

fmt.Println(string(j))
Output:

{
  "properties":{
    "ident":{"default":200,"minimum":123,"type":"integer"},
    "last_name":{"minLength":10,"type":"string"}
  },
  "type":"object"
}

func PropertyNameTag

func PropertyNameTag(tag string) func(*ReflectContext)

PropertyNameTag sets up which field tag to use for property name, default "json".

func RootNullable added in v0.3.0

func RootNullable(rc *ReflectContext)

RootNullable enables nullability (by pointer) for root schema, disabled by default.

func RootRef

func RootRef(rc *ReflectContext)

RootRef enables referencing root schema.

func SkipEmbeddedMapsSlices added in v0.3.7

func SkipEmbeddedMapsSlices(rc *ReflectContext)

SkipEmbeddedMapsSlices disables shortcutting into embedded maps and slices.

func SkipUnsupportedProperties added in v0.3.40

func SkipUnsupportedProperties(rc *ReflectContext)

SkipUnsupportedProperties skips properties with unsupported types (func, chan, etc...) instead of failing.

func StripDefinitionNamePrefix added in v0.3.25

func StripDefinitionNamePrefix(prefix ...string) func(rc *ReflectContext)

StripDefinitionNamePrefix checks if definition name has any of provided prefixes and removes first encountered.

Types

type AllOfExposer added in v0.3.25

type AllOfExposer interface {
	JSONSchemaAllOf() []interface{}
}

AllOfExposer exposes "allOf" items as list of samples.

func AllOf added in v0.3.34

func AllOf(v ...interface{}) AllOfExposer

AllOf exposes list of values as JSON "allOf" schema.

Example
r := jsonschema.Reflector{}

type Test struct {
	Foo jsonschema.AllOfExposer `json:"foo"`
	Bar jsonschema.AllOfExposer `json:"bar"`
}

tt := Test{
	Foo: jsonschema.AllOf(1.23, "abc"),
	Bar: jsonschema.AllOf(123, true),
}

s, _ := r.Reflect(tt, jsonschema.RootRef)
b, _ := assertjson.MarshalIndentCompact(s, "", " ", 100)

fmt.Println("Complex schema:", string(b))

s, _ = r.Reflect(jsonschema.AllOf(123, true), jsonschema.RootRef)
b, _ = assertjson.MarshalIndentCompact(s, "", " ", 100)

fmt.Println("Simple schema:", string(b))
Output:

Complex schema: {
 "$ref":"#/definitions/JsonschemaGoTestTest",
 "definitions":{
  "JsonschemaGoTestTest":{
   "properties":{
    "bar":{"allOf":[{"type":"integer"},{"type":"boolean"}]},
    "foo":{"allOf":[{"type":"number"},{"type":"string"}]}
   },
   "type":"object"
  }
 }
}
Simple schema: {"allOf":[{"type":"integer"},{"type":"boolean"}]}

type AnyOfExposer added in v0.3.25

type AnyOfExposer interface {
	JSONSchemaAnyOf() []interface{}
}

AnyOfExposer exposes "anyOf" items as list of samples.

func AnyOf added in v0.3.34

func AnyOf(v ...interface{}) AnyOfExposer

AnyOf exposes list of values as JSON "anyOf" schema.

Example
r := jsonschema.Reflector{}

type Test struct {
	Foo jsonschema.AnyOfExposer `json:"foo"`
	Bar jsonschema.AnyOfExposer `json:"bar"`
}

tt := Test{
	Foo: jsonschema.AnyOf(1.23, "abc"),
	Bar: jsonschema.AnyOf(123, true),
}

s, _ := r.Reflect(tt, jsonschema.RootRef)
b, _ := assertjson.MarshalIndentCompact(s, "", " ", 100)

fmt.Println("Complex schema:", string(b))

s, _ = r.Reflect(jsonschema.AnyOf(123, true), jsonschema.RootRef)
b, _ = assertjson.MarshalIndentCompact(s, "", " ", 100)

fmt.Println("Simple schema:", string(b))
Output:

Complex schema: {
 "$ref":"#/definitions/JsonschemaGoTestTest",
 "definitions":{
  "JsonschemaGoTestTest":{
   "properties":{
    "bar":{"anyOf":[{"type":"integer"},{"type":"boolean"}]},
    "foo":{"anyOf":[{"type":"number"},{"type":"string"}]}
   },
   "type":"object"
  }
 }
}
Simple schema: {"anyOf":[{"type":"integer"},{"type":"boolean"}]}

type Date added in v0.3.14

type Date time.Time

Date is a date represented in YYYY-MM-DD format.

func (Date) MarshalJSON added in v0.3.14

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

MarshalJSON marshals date in standard format.

func (Date) MarshalText added in v0.3.14

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

MarshalText marshals date in standard format.

func (*Date) UnmarshalJSON added in v0.3.14

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

UnmarshalJSON unmarshals date in standard format.

func (*Date) UnmarshalText added in v0.3.14

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

UnmarshalText loads date from a standard format value.

type DependenciesAdditionalProperties

type DependenciesAdditionalProperties struct {
	SchemaOrBool *SchemaOrBool `json:"-"`
	StringArray  []string      `json:"-"`
}

DependenciesAdditionalProperties structure is generated from "#[object]->dependencies->additionalProperties".

func (DependenciesAdditionalProperties) MarshalJSON

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

MarshalJSON encodes JSON.

func (*DependenciesAdditionalProperties) SchemaOrBoolEns added in v0.2.2

func (d *DependenciesAdditionalProperties) SchemaOrBoolEns() *SchemaOrBool

SchemaOrBoolEns ensures returned SchemaOrBool is not nil.

func (*DependenciesAdditionalProperties) UnmarshalJSON

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

UnmarshalJSON decodes JSON.

func (*DependenciesAdditionalProperties) WithSchemaOrBool

WithSchemaOrBool sets SchemaOrBool value.

func (*DependenciesAdditionalProperties) WithStringArray

WithStringArray sets StringArray value.

type Described

type Described interface {
	Description() string
}

Described exposes description.

type ElseExposer added in v0.3.25

type ElseExposer interface {
	JSONSchemaElse() interface{}
}

ElseExposer exposes "else" schema as a sample.

type Enum

type Enum interface {
	Enum() []interface{}
}

Enum returns the enumerated acceptable values.

Example
package main

import (
	"fmt"

	"github.com/swaggest/assertjson"
	"github.com/swaggest/jsonschema-go"
)

type WeekDay string

func (WeekDay) Enum() []interface{} {
	return []interface{}{
		"Monday",
		"Tuesday",
		"Wednesday",
		"Thursday",
		"Friday",
		"Saturday",
		"Sunday",
	}
}

type Shop struct {
	Days  []WeekDay `json:"days,omitempty"`  // This property uses dedicated named type to express enum.
	Days2 []string  `json:"days2,omitempty"` // This property uses schema preparer to set up enum.

	// This scalar property uses field tag to set up enum.
	Day string `json:"day" enum:"Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday"`
}

var _ jsonschema.Preparer = Shop{}

func (Shop) PrepareJSONSchema(schema *jsonschema.Schema) error {
	schema.Properties["days2"].TypeObject.WithEnum(
		"Monday",
		"Tuesday",
		"Wednesday",
		"Thursday",
		"Friday",
		"Saturday",
		"Sunday",
	)

	return nil
}

func main() {
	reflector := jsonschema.Reflector{}

	s, err := reflector.Reflect(Shop{}, jsonschema.StripDefinitionNamePrefix("JsonschemaGoTest"))
	if err != nil {
		panic(err)
	}

	j, err := assertjson.MarshalIndentCompact(s, "", "  ", 80)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(j))
}
Output:

{
  "definitions":{
    "WeekDay":{
      "enum":["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],
      "type":"string"
    }
  },
  "properties":{
    "day":{
      "enum":["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],
      "type":"string"
    },
    "days":{"items":{"$ref":"#/definitions/WeekDay"},"type":"array"},
    "days2":{
      "items":{"type":"string"},
      "enum":["Monday","Tuesday","Wednesday","Thursday","Friday","Saturday","Sunday"],
      "type":"array"
    }
  },
  "type":"object"
}

type Exposer

type Exposer interface {
	JSONSchema() (Schema, error)
}

Exposer exposes JSON Schema.

Example
package main

import (
	"fmt"

	"github.com/swaggest/assertjson"
	"github.com/swaggest/jsonschema-go"
)

// ParentOfExposer is an example structure.
type ParentOfExposer struct {
	Bar Exposer `json:"bar"`
}

// Exposer is an example structure.
type Exposer struct {
	Foo string `json:"foo"`
}

var _ jsonschema.Exposer = Exposer{}

// JSONSchema returns raw JSON Schema bytes.
// Fields and tags of structure are ignored.
func (Exposer) JSONSchema() (jsonschema.Schema, error) {
	var schema jsonschema.Schema

	schema.AddType(jsonschema.Object)
	schema.WithDescription("Custom description.")

	return schema, nil
}

func main() {
	reflector := jsonschema.Reflector{}

	s, err := reflector.Reflect(ParentOfExposer{}, jsonschema.StripDefinitionNamePrefix("JsonschemaGoTest"))
	if err != nil {
		panic(err)
	}

	j, err := assertjson.MarshalIndentCompact(s, "", "  ", 80)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(j))
}
Output:

{
  "definitions":{"Exposer":{"description":"Custom description.","type":"object"}},
  "properties":{"bar":{"$ref":"#/definitions/Exposer"}},"type":"object"
}

type IfExposer added in v0.3.25

type IfExposer interface {
	JSONSchemaIf() interface{}
}

IfExposer exposes "if" schema as a sample.

type IgnoreTypeName added in v0.3.1

type IgnoreTypeName interface {
	IgnoreTypeName()
}

IgnoreTypeName is a marker interface to ignore type name of mapped value and use original.

type InterceptPropertyFunc

type InterceptPropertyFunc func(name string, field reflect.StructField, propertySchema *Schema) error

InterceptPropertyFunc can intercept field reflection to control or modify schema.

Return ErrSkipProperty to avoid adding this property to parent Schema.Properties. Pointer to parent Schema is available in propertySchema.Parent.

type InterceptTypeFunc

type InterceptTypeFunc func(reflect.Value, *Schema) (bool, error)

InterceptTypeFunc can intercept type reflection to control or modify schema.

True bool result demands no further processing for the Schema.

type Items

type Items struct {
	SchemaOrBool *SchemaOrBool  `json:"-"`
	SchemaArray  []SchemaOrBool `json:"-"`
}

Items structure is generated from "#[object]->items".

func (Items) MarshalJSON

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

MarshalJSON encodes JSON.

func (*Items) SchemaOrBoolEns added in v0.2.2

func (i *Items) SchemaOrBoolEns() *SchemaOrBool

SchemaOrBoolEns ensures returned SchemaOrBool is not nil.

func (*Items) UnmarshalJSON

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

UnmarshalJSON decodes JSON.

func (*Items) WithSchemaArray

func (i *Items) WithSchemaArray(val ...SchemaOrBool) *Items

WithSchemaArray sets SchemaArray value.

func (*Items) WithSchemaOrBool

func (i *Items) WithSchemaOrBool(val SchemaOrBool) *Items

WithSchemaOrBool sets SchemaOrBool value.

type NamedEnum

type NamedEnum interface {
	NamedEnum() ([]interface{}, []string)
}

NamedEnum returns the enumerated acceptable values with according string names.

type NotExposer added in v0.3.25

type NotExposer interface {
	JSONSchemaNot() interface{}
}

NotExposer exposes "not" schema as a sample.

type OneOfExposer added in v0.3.25

type OneOfExposer interface {
	JSONSchemaOneOf() []interface{}
}

OneOfExposer exposes "oneOf" items as list of samples.

Example
package main

import (
	"fmt"

	"github.com/swaggest/assertjson"
	"github.com/swaggest/jsonschema-go"
)

// ParentOfOneOfExposer is an example structure.
type ParentOfOneOfExposer struct {
	Bar OneOfExposer `json:"bar"`
}

// OneOfExposer is an example structure.
type OneOfExposer struct{}

type OneOf1 struct {
	Foo string `json:"foo" required:"true"`
}

type OneOf2 struct {
	Baz string `json:"baz" required:"true"`
}

var _ jsonschema.OneOfExposer = OneOfExposer{}

func (OneOfExposer) JSONSchemaOneOf() []interface{} {
	return []interface{}{
		OneOf1{}, OneOf2{},
	}
}

func main() {
	reflector := jsonschema.Reflector{}

	s, err := reflector.Reflect(ParentOfOneOfExposer{}, jsonschema.StripDefinitionNamePrefix("JsonschemaGoTest"))
	if err != nil {
		panic(err)
	}

	j, err := assertjson.MarshalIndentCompact(s, "", "  ", 80)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(j))
}
Output:

{
  "definitions":{
    "OneOf1":{
      "required":["foo"],"properties":{"foo":{"type":"string"}},"type":"object"
    },
    "OneOf2":{
      "required":["baz"],"properties":{"baz":{"type":"string"}},"type":"object"
    },
    "OneOfExposer":{
      "type":"object",
      "oneOf":[{"$ref":"#/definitions/OneOf1"},{"$ref":"#/definitions/OneOf2"}]
    }
  },
  "properties":{"bar":{"$ref":"#/definitions/OneOfExposer"}},"type":"object"
}

func OneOf added in v0.3.34

func OneOf(v ...interface{}) OneOfExposer

OneOf exposes list of values as JSON "oneOf" schema.

Example
r := jsonschema.Reflector{}

type Test struct {
	Foo jsonschema.OneOfExposer `json:"foo"`
	Bar jsonschema.OneOfExposer `json:"bar"`
}

tt := Test{
	Foo: jsonschema.OneOf(1.23, "abc"),
	Bar: jsonschema.OneOf(123, true),
}

s, _ := r.Reflect(tt, jsonschema.RootRef)
b, _ := assertjson.MarshalIndentCompact(s, "", " ", 100)

fmt.Println("Complex schema:", string(b))

s, _ = r.Reflect(jsonschema.OneOf(123, true), jsonschema.RootRef)
b, _ = assertjson.MarshalIndentCompact(s, "", " ", 100)

fmt.Println("Simple schema:", string(b))
Output:

Complex schema: {
 "$ref":"#/definitions/JsonschemaGoTestTest",
 "definitions":{
  "JsonschemaGoTestTest":{
   "properties":{
    "bar":{"oneOf":[{"type":"integer"},{"type":"boolean"}]},
    "foo":{"oneOf":[{"type":"number"},{"type":"string"}]}
   },
   "type":"object"
  }
 }
}
Simple schema: {"oneOf":[{"type":"integer"},{"type":"boolean"}]}

type Preparer

type Preparer interface {
	PrepareJSONSchema(schema *Schema) error
}

Preparer alters reflected JSON Schema.

Example
package main

import (
	"fmt"

	"github.com/swaggest/assertjson"
	"github.com/swaggest/jsonschema-go"
)

// ParentOfPreparer is an example structure.
type ParentOfPreparer struct {
	Bar Preparer `json:"bar"`
}

// Preparer is an example structure.
type Preparer struct {
	Foo string `json:"foo"`
}

var _ jsonschema.Preparer = Preparer{}

func (s Preparer) PrepareJSONSchema(schema *jsonschema.Schema) error {
	schema.WithDescription("Custom description.")
	schema.Properties["foo"].TypeObject.WithEnum("one", "two", "three")

	return nil
}

func main() {
	reflector := jsonschema.Reflector{}

	s, err := reflector.Reflect(ParentOfPreparer{}, jsonschema.StripDefinitionNamePrefix("JsonschemaGoTest"))
	if err != nil {
		panic(err)
	}

	j, err := assertjson.MarshalIndentCompact(s, "", "  ", 80)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(j))
}
Output:

{
  "definitions":{
    "Preparer":{
      "description":"Custom description.",
      "properties":{"foo":{"enum":["one","two","three"],"type":"string"}},
      "type":"object"
    }
  },
  "properties":{"bar":{"$ref":"#/definitions/Preparer"}},"type":"object"
}

type RawExposer added in v0.2.3

type RawExposer interface {
	JSONSchemaBytes() ([]byte, error)
}

RawExposer exposes JSON Schema as JSON bytes.

Example
package main

import (
	"fmt"

	"github.com/swaggest/assertjson"
	"github.com/swaggest/jsonschema-go"
)

// ParentOfRawExposer is an example structure.
type ParentOfRawExposer struct {
	Bar RawExposer `json:"bar"`
}

// RawExposer is an example structure.
type RawExposer struct {
	Foo string `json:"foo"`
}

var _ jsonschema.RawExposer = RawExposer{}

// JSONSchemaBytes returns raw JSON Schema bytes.
// Fields and tags of structure are ignored.
func (s RawExposer) JSONSchemaBytes() ([]byte, error) {
	return []byte(`{"description":"Custom description.","type":"object","properties":{"foo":{"type":"string"}}}`), nil
}

func main() {
	reflector := jsonschema.Reflector{}

	s, err := reflector.Reflect(ParentOfRawExposer{}, jsonschema.StripDefinitionNamePrefix("JsonschemaGoTest"))
	if err != nil {
		panic(err)
	}

	j, err := assertjson.MarshalIndentCompact(s, "", "  ", 80)
	if err != nil {
		panic(err)
	}

	fmt.Println(string(j))
}
Output:

{
  "definitions":{
    "RawExposer":{
      "description":"Custom description.",
      "properties":{"foo":{"type":"string"}},"type":"object"
    }
  },
  "properties":{"bar":{"$ref":"#/definitions/RawExposer"}},"type":"object"
}

type Ref

type Ref struct {
	Path string
	Name string
}

Ref is a definition reference.

func (Ref) Schema

func (r Ref) Schema() Schema

Schema creates schema instance from reference.

type ReflectContext

type ReflectContext struct {
	// Context allows communicating user data between reflection steps.
	context.Context

	// DefName returns custom definition name for a type, can be nil.
	DefName func(t reflect.Type, defaultDefName string) string

	// CollectDefinitions is triggered when named schema is created, can be nil.
	// Non-empty CollectDefinitions disables collection of definitions into resulting schema.
	CollectDefinitions func(name string, schema Schema)

	// DefinitionsPrefix defines location of named schemas, default #/definitions/.
	DefinitionsPrefix string

	// PropertyNameTag enables property naming from a field tag, e.g. `header:"first_name"`.
	PropertyNameTag string

	// PropertyNameMapping enables property name mapping from a struct field name, e.g. "FirstName":"first_name".
	// Only applicable to top-level properties (including embedded).
	PropertyNameMapping map[string]string

	// ProcessWithoutTags enables processing fields without any tags specified.
	ProcessWithoutTags bool

	// UnnamedFieldWithTag enables a requirement that name tag is present
	// when processing _ fields to set up parent schema, e.g.
	//   _ struct{} `header:"_" additionalProperties:"false"`.
	UnnamedFieldWithTag bool

	// EnvelopNullability enables `anyOf` enveloping of "type":"null" instead of injecting into definition.
	EnvelopNullability bool

	InlineRefs   bool
	RootRef      bool
	RootNullable bool

	// SkipEmbeddedMapsSlices disables shortcutting into embedded maps and slices.
	SkipEmbeddedMapsSlices bool

	// InterceptType is called before and after type processing.
	// So it may be called twice for the same type, first time with empty Schema and
	// second time with fully processed schema.
	InterceptType     InterceptTypeFunc
	InterceptProperty InterceptPropertyFunc

	// SkipNonConstraints disables parsing of `default` and `example` field tags.
	SkipNonConstraints bool

	// SkipUnsupportedProperties skips properties with unsupported types (func, chan, etc...) instead of failing.
	SkipUnsupportedProperties bool

	Path []string
	// contains filtered or unexported fields
}

ReflectContext accompanies single reflect operation.

type Reflector

type Reflector struct {
	DefaultOptions []func(*ReflectContext)
	// contains filtered or unexported fields
}

Reflector creates JSON Schemas from Go values.

func (*Reflector) AddTypeMapping

func (r *Reflector) AddTypeMapping(src, dst interface{})

AddTypeMapping creates substitution link between types of src and dst when reflecting JSON Schema.

func (*Reflector) InterceptDefName added in v0.3.20

func (r *Reflector) InterceptDefName(f func(t reflect.Type, defaultDefName string) string)

InterceptDefName allows modifying reflected definition names.

func (*Reflector) Reflect

func (r *Reflector) Reflect(i interface{}, options ...func(rc *ReflectContext)) (Schema, error)

Reflect walks Go value and builds its JSON Schema based on types and field tags.

Values can be populated from field tags of original field:

type MyObj struct {
   BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
   SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
}

Note: field tags are only applied to inline schemas, if you use named type then referenced schema will be created and tags will be ignored. This happens because referenced schema can be used in multiple fields with conflicting tags, therefore customization of referenced schema has to done on the type itself via RawExposer, Exposer or Preparer.

These tags can be used:

Unnamed fields can be used to configure parent schema:

type MyObj struct {
   BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
   SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
   _             struct{} `additionalProperties:"false" description:"MyObj is my object."`
}

In case of a structure with multiple name tags, you can enable filtering of unnamed fields with ReflectContext.UnnamedFieldWithTag option and add matching name tags to structure (e.g. query:"_").

type MyObj struct {
   BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
   SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
   // These parent schema tags would only be applied to `query` schema reflection (not for `json`).
   _ struct{} `query:"_" additionalProperties:"false" description:"MyObj is my object."`
}

Additionally there are structure can implement any of special interfaces for fine-grained Schema control: RawExposer, Exposer, Preparer.

These interfaces allow exposing particular schema keywords: Titled, Described, Enum, NamedEnum.

Available options:

CollectDefinitions
DefinitionsPrefix
PropertyNameTag
InterceptType
InterceptProperty
InlineRefs
RootNullable
RootRef
StripDefinitionNamePrefix
PropertyNameMapping
ProcessWithoutTags
SkipEmbeddedMapsSlices
SkipUnsupportedProperties
Example
reflector := jsonschema.Reflector{}

// Create custom schema mapping for 3rd party type.
uuidDef := jsonschema.Schema{}
uuidDef.AddType(jsonschema.String)
uuidDef.WithFormat("uuid")
uuidDef.WithExamples("248df4b7-aa70-47b8-a036-33ac447e668d")

// Map 3rd party type with your own schema.
reflector.AddTypeMapping(UUID{}, uuidDef)

// Map the type that does not expose schema information to a type with schema information.
reflector.AddTypeMapping(new(WeirdResp), new(Resp))

// Modify default definition names to better match your packages structure.
reflector.InterceptDefName(func(t reflect.Type, defaultDefName string) string {
	return strings.TrimPrefix(defaultDefName, "JsonschemaGoTest")
})

// Create schema from Go value.
schema, err := reflector.Reflect(new(Resp))
if err != nil {
	log.Fatal(err)
}

j, err := json.MarshalIndent(schema, "", " ")
if err != nil {
	log.Fatal(err)
}

fmt.Println(string(j))
Output:

{
 "title": "Sample Response",
 "description": "This is a sample response.",
 "definitions": {
  "NamedAnything": {},
  "UUID": {
   "examples": [
    "248df4b7-aa70-47b8-a036-33ac447e668d"
   ],
   "type": "string",
   "format": "uuid"
  }
 },
 "properties": {
  "arrayOfAnything": {
   "items": {},
   "type": "array"
  },
  "arrayOfNamedAnything": {
   "items": {
    "$ref": "#/definitions/NamedAnything"
   },
   "type": "array"
  },
  "field1": {
   "type": "integer"
  },
  "field2": {
   "type": "string"
  },
  "info": {
   "required": [
    "foo"
   ],
   "properties": {
    "bar": {
     "description": "This is Bar.",
     "type": "number"
    },
    "foo": {
     "default": "baz",
     "pattern": "\\d+",
     "type": "string"
    }
   },
   "type": "object"
  },
  "map": {
   "additionalProperties": {
    "type": "integer"
   },
   "type": "object"
  },
  "mapOfAnything": {
   "additionalProperties": {},
   "type": "object"
  },
  "nullableWhatever": {},
  "parent": {
   "$ref": "#"
  },
  "recursiveArray": {
   "items": {
    "$ref": "#"
   },
   "type": "array"
  },
  "recursiveStructArray": {
   "items": {
    "$ref": "#"
   },
   "type": "array"
  },
  "uuid": {
   "$ref": "#/definitions/UUID"
  },
  "whatever": {}
 },
 "type": "object",
 "x-foo": "bar"
}
Example (Simple)
type MyStruct struct {
	Amount float64  `json:"amount" minimum:"10.5" example:"20.6" required:"true"`
	Abc    string   `json:"abc" pattern:"[abc]"`
	_      struct{} `additionalProperties:"false"`                   // Tags of unnamed field are applied to parent schema.
	_      struct{} `title:"My Struct" description:"Holds my data."` // Multiple unnamed fields can be used.
}

reflector := jsonschema.Reflector{}

schema, err := reflector.Reflect(MyStruct{})
if err != nil {
	log.Fatal(err)
}

j, err := json.MarshalIndent(schema, "", " ")
if err != nil {
	log.Fatal(err)
}

fmt.Println(string(j))
Output:

{
 "title": "My Struct",
 "description": "Holds my data.",
 "required": [
  "amount"
 ],
 "additionalProperties": false,
 "properties": {
  "abc": {
   "pattern": "[abc]",
   "type": "string"
  },
  "amount": {
   "examples": [
    20.6
   ],
   "minimum": 10.5,
   "type": "number"
  }
 },
 "type": "object"
}

type Schema

type Schema struct {
	ID                   *string                                     `json:"$id,omitempty"`     // Format: uri-reference.
	Schema               *string                                     `json:"$schema,omitempty"` // Format: uri.
	Ref                  *string                                     `json:"$ref,omitempty"`    // Format: uri-reference.
	Comment              *string                                     `json:"$comment,omitempty"`
	Title                *string                                     `json:"title,omitempty"`
	Description          *string                                     `json:"description,omitempty"`
	Default              *interface{}                                `json:"default,omitempty"`
	ReadOnly             *bool                                       `json:"readOnly,omitempty"`
	Examples             []interface{}                               `json:"examples,omitempty"`
	MultipleOf           *float64                                    `json:"multipleOf,omitempty"`
	Maximum              *float64                                    `json:"maximum,omitempty"`
	ExclusiveMaximum     *float64                                    `json:"exclusiveMaximum,omitempty"`
	Minimum              *float64                                    `json:"minimum,omitempty"`
	ExclusiveMinimum     *float64                                    `json:"exclusiveMinimum,omitempty"`
	MaxLength            *int64                                      `json:"maxLength,omitempty"`
	MinLength            int64                                       `json:"minLength,omitempty"`
	Pattern              *string                                     `json:"pattern,omitempty"`         // Format: regex.
	AdditionalItems      *SchemaOrBool                               `json:"additionalItems,omitempty"` // Core schema meta-schema.
	Items                *Items                                      `json:"items,omitempty"`
	MaxItems             *int64                                      `json:"maxItems,omitempty"`
	MinItems             int64                                       `json:"minItems,omitempty"`
	UniqueItems          *bool                                       `json:"uniqueItems,omitempty"`
	Contains             *SchemaOrBool                               `json:"contains,omitempty"` // Core schema meta-schema.
	MaxProperties        *int64                                      `json:"maxProperties,omitempty"`
	MinProperties        int64                                       `json:"minProperties,omitempty"`
	Required             []string                                    `json:"required,omitempty"`
	AdditionalProperties *SchemaOrBool                               `json:"additionalProperties,omitempty"` // Core schema meta-schema.
	Definitions          map[string]SchemaOrBool                     `json:"definitions,omitempty"`
	Properties           map[string]SchemaOrBool                     `json:"properties,omitempty"`
	PatternProperties    map[string]SchemaOrBool                     `json:"patternProperties,omitempty"`
	Dependencies         map[string]DependenciesAdditionalProperties `json:"dependencies,omitempty"`
	PropertyNames        *SchemaOrBool                               `json:"propertyNames,omitempty"` // Core schema meta-schema.
	Const                *interface{}                                `json:"const,omitempty"`
	Enum                 []interface{}                               `json:"enum,omitempty"`
	Type                 *Type                                       `json:"type,omitempty"`
	Format               *string                                     `json:"format,omitempty"`
	ContentMediaType     *string                                     `json:"contentMediaType,omitempty"`
	ContentEncoding      *string                                     `json:"contentEncoding,omitempty"`
	If                   *SchemaOrBool                               `json:"if,omitempty"`   // Core schema meta-schema.
	Then                 *SchemaOrBool                               `json:"then,omitempty"` // Core schema meta-schema.
	Else                 *SchemaOrBool                               `json:"else,omitempty"` // Core schema meta-schema.
	AllOf                []SchemaOrBool                              `json:"allOf,omitempty"`
	AnyOf                []SchemaOrBool                              `json:"anyOf,omitempty"`
	OneOf                []SchemaOrBool                              `json:"oneOf,omitempty"`
	Not                  *SchemaOrBool                               `json:"not,omitempty"` // Core schema meta-schema.
	ExtraProperties      map[string]interface{}                      `json:"-"`             // All unmatched properties.
	ReflectType          reflect.Type                                `json:"-"`
	Parent               *Schema                                     `json:"-"`
}

Schema structure is generated from "#[object]".

Core schema meta-schema.

func (*Schema) AddType

func (s *Schema) AddType(t SimpleType)

AddType adds simple type to Schema.

If type is already there it is ignored.

func (*Schema) AdditionalItemsEns added in v0.2.2

func (s *Schema) AdditionalItemsEns() *SchemaOrBool

AdditionalItemsEns ensures returned AdditionalItems is not nil.

func (*Schema) AdditionalPropertiesEns added in v0.2.2

func (s *Schema) AdditionalPropertiesEns() *SchemaOrBool

AdditionalPropertiesEns ensures returned AdditionalProperties is not nil.

func (*Schema) ContainsEns added in v0.2.2

func (s *Schema) ContainsEns() *SchemaOrBool

ContainsEns ensures returned Contains is not nil.

func (*Schema) ElseEns added in v0.2.2

func (s *Schema) ElseEns() *SchemaOrBool

ElseEns ensures returned Else is not nil.

func (*Schema) HasType added in v0.3.4

func (s *Schema) HasType(t SimpleType) bool

HasType checks if Schema has a simple type.

func (*Schema) IfEns added in v0.2.2

func (s *Schema) IfEns() *SchemaOrBool

IfEns ensures returned If is not nil.

func (Schema) IgnoreTypeName added in v0.3.1

func (s Schema) IgnoreTypeName()

IgnoreTypeName instructs reflector to keep original type name during mapping.

func (Schema) IsTrivial added in v0.3.9

func (s Schema) IsTrivial(refResolvers ...func(string) (SchemaOrBool, bool)) bool

IsTrivial is true if schema does not contain validation constraints other than type.

Trivial schema can define trivial items or properties. This flag can be used to skip validation of structures that check types during decoding.

func (*Schema) ItemsEns added in v0.2.2

func (s *Schema) ItemsEns() *Items

ItemsEns ensures returned Items is not nil.

func (Schema) JSONSchema

func (s Schema) JSONSchema() (Schema, error)

JSONSchema implements Exposer.

func (Schema) JSONSchemaBytes added in v0.2.3

func (s Schema) JSONSchemaBytes() ([]byte, error)

JSONSchemaBytes exposes JSON Schema as raw JSON bytes.

func (Schema) MarshalJSON

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

MarshalJSON encodes JSON.

func (*Schema) NotEns added in v0.2.2

func (s *Schema) NotEns() *SchemaOrBool

NotEns ensures returned Not is not nil.

func (*Schema) PropertyNamesEns added in v0.2.2

func (s *Schema) PropertyNamesEns() *SchemaOrBool

PropertyNamesEns ensures returned PropertyNames is not nil.

func (*Schema) ThenEns added in v0.2.2

func (s *Schema) ThenEns() *SchemaOrBool

ThenEns ensures returned Then is not nil.

func (*Schema) ToSchemaOrBool

func (s *Schema) ToSchemaOrBool() SchemaOrBool

ToSchemaOrBool creates SchemaOrBool instance from Schema.

func (*Schema) TypeEns added in v0.2.2

func (s *Schema) TypeEns() *Type

TypeEns ensures returned Type is not nil.

func (*Schema) UnmarshalJSON

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

UnmarshalJSON decodes JSON.

func (*Schema) WithAdditionalItems

func (s *Schema) WithAdditionalItems(val SchemaOrBool) *Schema

WithAdditionalItems sets AdditionalItems value.

func (*Schema) WithAdditionalProperties

func (s *Schema) WithAdditionalProperties(val SchemaOrBool) *Schema

WithAdditionalProperties sets AdditionalProperties value.

func (*Schema) WithAllOf

func (s *Schema) WithAllOf(val ...SchemaOrBool) *Schema

WithAllOf sets AllOf value.

func (*Schema) WithAnyOf

func (s *Schema) WithAnyOf(val ...SchemaOrBool) *Schema

WithAnyOf sets AnyOf value.

func (*Schema) WithComment

func (s *Schema) WithComment(val string) *Schema

WithComment sets Comment value.

func (*Schema) WithConst

func (s *Schema) WithConst(val interface{}) *Schema

WithConst sets Const value.

func (*Schema) WithContains

func (s *Schema) WithContains(val SchemaOrBool) *Schema

WithContains sets Contains value.

func (*Schema) WithContentEncoding

func (s *Schema) WithContentEncoding(val string) *Schema

WithContentEncoding sets ContentEncoding value.

func (*Schema) WithContentMediaType

func (s *Schema) WithContentMediaType(val string) *Schema

WithContentMediaType sets ContentMediaType value.

func (*Schema) WithDefault

func (s *Schema) WithDefault(val interface{}) *Schema

WithDefault sets Default value.

func (*Schema) WithDefinitions

func (s *Schema) WithDefinitions(val map[string]SchemaOrBool) *Schema

WithDefinitions sets Definitions value.

func (*Schema) WithDefinitionsItem

func (s *Schema) WithDefinitionsItem(key string, val SchemaOrBool) *Schema

WithDefinitionsItem sets Definitions item value.

func (*Schema) WithDependencies

func (s *Schema) WithDependencies(val map[string]DependenciesAdditionalProperties) *Schema

WithDependencies sets Dependencies value.

func (*Schema) WithDependenciesItem

func (s *Schema) WithDependenciesItem(key string, val DependenciesAdditionalProperties) *Schema

WithDependenciesItem sets Dependencies item value.

func (*Schema) WithDescription

func (s *Schema) WithDescription(val string) *Schema

WithDescription sets Description value.

func (*Schema) WithElse

func (s *Schema) WithElse(val SchemaOrBool) *Schema

WithElse sets Else value.

func (*Schema) WithEnum

func (s *Schema) WithEnum(val ...interface{}) *Schema

WithEnum sets Enum value.

func (*Schema) WithExamples

func (s *Schema) WithExamples(val ...interface{}) *Schema

WithExamples sets Examples value.

func (*Schema) WithExclusiveMaximum

func (s *Schema) WithExclusiveMaximum(val float64) *Schema

WithExclusiveMaximum sets ExclusiveMaximum value.

func (*Schema) WithExclusiveMinimum

func (s *Schema) WithExclusiveMinimum(val float64) *Schema

WithExclusiveMinimum sets ExclusiveMinimum value.

func (*Schema) WithExtraProperties

func (s *Schema) WithExtraProperties(val map[string]interface{}) *Schema

WithExtraProperties sets ExtraProperties value.

func (*Schema) WithExtraPropertiesItem

func (s *Schema) WithExtraPropertiesItem(key string, val interface{}) *Schema

WithExtraPropertiesItem sets ExtraProperties item value.

func (*Schema) WithFormat

func (s *Schema) WithFormat(val string) *Schema

WithFormat sets Format value.

func (*Schema) WithID

func (s *Schema) WithID(val string) *Schema

WithID sets ID value.

func (*Schema) WithIf

func (s *Schema) WithIf(val SchemaOrBool) *Schema

WithIf sets If value.

func (*Schema) WithItems

func (s *Schema) WithItems(val Items) *Schema

WithItems sets Items value.

func (*Schema) WithMaxItems

func (s *Schema) WithMaxItems(val int64) *Schema

WithMaxItems sets MaxItems value.

func (*Schema) WithMaxLength

func (s *Schema) WithMaxLength(val int64) *Schema

WithMaxLength sets MaxLength value.

func (*Schema) WithMaxProperties

func (s *Schema) WithMaxProperties(val int64) *Schema

WithMaxProperties sets MaxProperties value.

func (*Schema) WithMaximum

func (s *Schema) WithMaximum(val float64) *Schema

WithMaximum sets Maximum value.

func (*Schema) WithMinItems

func (s *Schema) WithMinItems(val int64) *Schema

WithMinItems sets MinItems value.

func (*Schema) WithMinLength

func (s *Schema) WithMinLength(val int64) *Schema

WithMinLength sets MinLength value.

func (*Schema) WithMinProperties

func (s *Schema) WithMinProperties(val int64) *Schema

WithMinProperties sets MinProperties value.

func (*Schema) WithMinimum

func (s *Schema) WithMinimum(val float64) *Schema

WithMinimum sets Minimum value.

func (*Schema) WithMultipleOf

func (s *Schema) WithMultipleOf(val float64) *Schema

WithMultipleOf sets MultipleOf value.

func (*Schema) WithNot

func (s *Schema) WithNot(val SchemaOrBool) *Schema

WithNot sets Not value.

func (*Schema) WithOneOf

func (s *Schema) WithOneOf(val ...SchemaOrBool) *Schema

WithOneOf sets OneOf value.

func (*Schema) WithPattern

func (s *Schema) WithPattern(val string) *Schema

WithPattern sets Pattern value.

func (*Schema) WithPatternProperties

func (s *Schema) WithPatternProperties(val map[string]SchemaOrBool) *Schema

WithPatternProperties sets PatternProperties value.

func (*Schema) WithPatternPropertiesItem

func (s *Schema) WithPatternPropertiesItem(key string, val SchemaOrBool) *Schema

WithPatternPropertiesItem sets PatternProperties item value.

func (*Schema) WithProperties

func (s *Schema) WithProperties(val map[string]SchemaOrBool) *Schema

WithProperties sets Properties value.

func (*Schema) WithPropertiesItem

func (s *Schema) WithPropertiesItem(key string, val SchemaOrBool) *Schema

WithPropertiesItem sets Properties item value.

func (*Schema) WithPropertyNames

func (s *Schema) WithPropertyNames(val SchemaOrBool) *Schema

WithPropertyNames sets PropertyNames value.

func (*Schema) WithReadOnly

func (s *Schema) WithReadOnly(val bool) *Schema

WithReadOnly sets ReadOnly value.

func (*Schema) WithRef

func (s *Schema) WithRef(val string) *Schema

WithRef sets Ref value.

func (*Schema) WithRequired

func (s *Schema) WithRequired(val ...string) *Schema

WithRequired sets Required value.

func (*Schema) WithSchema

func (s *Schema) WithSchema(val string) *Schema

WithSchema sets Schema value.

func (*Schema) WithThen

func (s *Schema) WithThen(val SchemaOrBool) *Schema

WithThen sets Then value.

func (*Schema) WithTitle

func (s *Schema) WithTitle(val string) *Schema

WithTitle sets Title value.

func (*Schema) WithType

func (s *Schema) WithType(val Type) *Schema

WithType sets Type value.

func (*Schema) WithUniqueItems

func (s *Schema) WithUniqueItems(val bool) *Schema

WithUniqueItems sets UniqueItems value.

type SchemaInliner added in v0.3.34

type SchemaInliner interface {
	InlineJSONSchema()
}

SchemaInliner is a marker interface to inline schema without creating a definition.

type SchemaOrBool

type SchemaOrBool struct {
	TypeObject  *Schema `json:"-"`
	TypeBoolean *bool   `json:"-"`
}

SchemaOrBool structure is generated from "#".

Core schema meta-schema.

func (SchemaOrBool) IsTrivial added in v0.3.9

func (s SchemaOrBool) IsTrivial(refResolvers ...func(string) (SchemaOrBool, bool)) bool

IsTrivial is true if schema does not contain validation constraints other than type.

func (SchemaOrBool) JSONSchemaBytes added in v0.2.3

func (s SchemaOrBool) JSONSchemaBytes() ([]byte, error)

JSONSchemaBytes exposes JSON Schema as raw JSON bytes.

func (SchemaOrBool) MarshalJSON

func (s SchemaOrBool) MarshalJSON() ([]byte, error)

MarshalJSON encodes JSON.

func (SchemaOrBool) ToSimpleMap added in v0.2.3

func (s SchemaOrBool) ToSimpleMap() (map[string]interface{}, error)

ToSimpleMap encodes JSON Schema as generic map.

func (*SchemaOrBool) TypeObjectEns added in v0.2.2

func (s *SchemaOrBool) TypeObjectEns() *Schema

TypeObjectEns ensures returned TypeObject is not nil.

func (*SchemaOrBool) UnmarshalJSON

func (s *SchemaOrBool) UnmarshalJSON(data []byte) error

UnmarshalJSON decodes JSON.

func (*SchemaOrBool) WithTypeBoolean

func (s *SchemaOrBool) WithTypeBoolean(val bool) *SchemaOrBool

WithTypeBoolean sets TypeBoolean value.

func (*SchemaOrBool) WithTypeObject

func (s *SchemaOrBool) WithTypeObject(val Schema) *SchemaOrBool

WithTypeObject sets TypeObject value.

type SimpleType

type SimpleType string

SimpleType is an enum type.

func (SimpleType) MarshalJSON

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

MarshalJSON encodes JSON.

func (SimpleType) ToSchemaOrBool added in v0.3.4

func (i SimpleType) ToSchemaOrBool() SchemaOrBool

ToSchemaOrBool creates SchemaOrBool instance from SimpleType.

func (SimpleType) Type

func (i SimpleType) Type() Type

Type references simple type.

func (*SimpleType) UnmarshalJSON

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

UnmarshalJSON decodes JSON.

type ThenExposer added in v0.3.25

type ThenExposer interface {
	JSONSchemaThen() interface{}
}

ThenExposer exposes "then" schema as a sample.

type Titled

type Titled interface {
	Title() string
}

Titled exposes title.

type Type

type Type struct {
	SimpleTypes             *SimpleType  `json:"-"`
	SliceOfSimpleTypeValues []SimpleType `json:"-"`
}

Type structure is generated from "#[object]->type".

func (Type) MarshalJSON

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

MarshalJSON encodes JSON.

func (*Type) UnmarshalJSON

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

UnmarshalJSON decodes JSON.

func (*Type) WithSimpleTypes

func (t *Type) WithSimpleTypes(val SimpleType) *Type

WithSimpleTypes sets SimpleTypes value.

func (*Type) WithSliceOfSimpleTypeValues

func (t *Type) WithSliceOfSimpleTypeValues(val ...SimpleType) *Type

WithSliceOfSimpleTypeValues sets SliceOfSimpleTypeValues value.

Jump to

Keyboard shortcuts

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