jsonschema

package module
v1.1.0 Latest Latest
Warning

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

Go to latest
Published: Feb 11, 2022 License: MIT Imports: 7 Imported by: 4

README

jsonschema Creates a json schema from a struct

This package can generate a json schema for a struct that is compatible with https://json-schema.org/

type ExampleStruct struct {
  Name string
  Field []int
  SomeOtherStruct OtherStruct
}

func main() {
  defsMap := map[string]jsonschema.Property{}
  schema, err := jsonschema.From(
    ExampleStruct{},
    "#/$defs/",
    func(key string, value jsonschema.Property) {
      defsMap[key] = value
    },
    func(key string) bool {
      _, ok := defsMap[key]
      return ok
    },
    nil,
  )

  if err != nil {
    log.Fatal(err)
  }

  schema.Defs = defs
}
Default applied rules:
  • A struct field is labeled as required when the data cannot be nil so strings,bool,int,float,struct, etc.. are required and []string, [8]int, *int, map[string]string are not required. You can overwrite this behavior by using jsonSchema struct tag
Supported struct tags:
  • json:
    • "-" Ignores the field
    • "other_name" Renames the field
  • jsonSchema:
    • "notRequired" Set the field are not required (by default all fields with the exeption of ptr, array, slice and map are set as required)
    • "required" Set the field as required
    • "deprecated" Mark the field as deprecated
    • "uniqueItems" Every array entry must be unique (Only for arrays)
    • "hidden" Do not expose field in the schema
    • "min=123" Set the minimum value or array length for the field
    • "max=123" Set the maximum value or array length for the field
  • description:"describe a property here" Set the description property

You can also chain jsonSchema tags using , for example: jsonSchema:"notRequired,deprecated"

Custom (Un)MarshalJSON

Sometimes you might want to define a custom schema for a type that implements the MarshalJSON and UnmarshalJSON methods.

You can define a custom definition like so:

var PhoneNumber string

func (PhoneNumber) JSONSchemaDescribe() jsonschema.Property {
	minLen := uint(3)
	return jsonschema.Property{
		Title:       "Phone number",
		Description: "This field can contain any kind phone number",
		Type:        jsonschema.PropertyTypeString,
		Examples: []json.RawMessage{
			[]byte("\"06 12345678\""),
			[]byte("\"+31 6 1234 5678\""),
		},
		MinLength: &minLen,
	}
}

Documentation

Index

Constants

View Source
const (
	// PropertyTypeNull represends nil values
	PropertyTypeNull = PropertyType("null")
	// PropertyTypeBoolean represends boolean values
	PropertyTypeBoolean = PropertyType("boolean")
	// PropertyTypeObject represends struct and map values
	PropertyTypeObject = PropertyType("object")
	// PropertyTypeArray represends slice and array values
	PropertyTypeArray = PropertyType("array")
	// PropertyTypeInteger represends int and uint values
	PropertyTypeInteger = PropertyType("integer")
	// PropertyTypeNumber represends float values
	PropertyTypeNumber = PropertyType("number")
	// PropertyTypeString represends string values
	PropertyTypeString = PropertyType("string")
)
View Source
const (
	// FormatDateTime derives from RFC 3339
	FormatDateTime = Format("date-time")
	// FormatDate derives from RFC 3339
	FormatDate = Format("date")
	// FormatTime derives from RFC 3339
	FormatTime = Format("time")
	// FormatDuration derives from RFC 3339
	FormatDuration = Format("duration")
	// FormatEmail as defined by the "Mailbox" ABNF rule in RFC 5321, section 4.1.2.
	FormatEmail = Format("email")
	// FormatIdnEmail as defined by the extended "Mailbox" ABNF rule in RFC 6531, section 3.3.
	FormatIdnEmail = Format("idn-email")
	// FormatHostname as defined by RFC 1123, section 2.1, including host names produced using the Punycode
	// algorithm specified in RFC 5891, section 4.4.
	FormatHostname = Format("hostname")
	// FormatIdnHostname as defined by either RFC 1123 as for hostname, or an internationalized hostname as defined
	// by RFC 5890, section 2.3.2.3.
	FormatIdnHostname = Format("idn-hostname")
	// FormatIPV4 is a ip version 4
	FormatIPV4 = Format("ipv4")
	// FormatIPV6 is a ip version 6
	FormatIPV6 = Format("ipv6")
	// FormatURI a valid uri derived from RFC3986
	FormatURI = Format("uri")
	// FormatURIReference a valid uri derived from RFC3986
	// either a URI or a relative-reference
	FormatURIReference = Format("uri-reference")
	// FormatIRI a valid uri derived from RFC3987
	FormatIRI = Format("iri")
	// FormatIRIReference a valid uri derived from RFC3987
	// either an IRI or a relative-reference
	FormatIRIReference = Format("iri-reference")
	// FormatUUID a valid uuid derived from RFC4122
	FormatUUID = Format("uui")
)
View Source
const VersionUsed = Version("https://json-schema.org/draft/2020-12/schema")

VersionUsed contains the schema version this package was build ontop

Variables

This section is empty.

Functions

This section is empty.

Types

type Describe

type Describe interface {
	JSONSchemaDescribe() Property
}

Describe can be implmented by a type to manually describe the type

type Format

type Format string

Format contains a expected data format

type Property

type Property struct {
	Title       string              `json:"title,omitempty"`
	Description string              `json:"description,omitempty"`
	Type        PropertyType        `json:"type,omitempty"`  // The data type
	Enum        []json.RawMessage   `json:"enum,omitempty"`  // The value should validate againest one of these
	Const       interface{}         `json:"const,omitempty"` // Equal to a enum with 1 value
	Deprecated  bool                `json:"deprecated,omitempty"`
	Default     interface{}         `json:"default,omitempty"`
	Examples    []json.RawMessage   `json:"examples,omitempty"`
	Format      Format              `json:"format,omitempty"`
	Ref         string              `json:"$ref,omitempty"`
	Defs        map[string]Property `json:"$defs,omitempty"`

	// Only in the root of the schema
	Schema Version `json:"$schema,omitempty"`
	ID     string  `json:"$id,omitempty"`

	// type == object
	Properties        map[string]Property `json:"properties,omitempty"` // required field
	Required          []string            `json:"required,omitempty"`
	MaxProperties     *uint               `json:"maxProperties,omitempty"`
	MinProperties     *uint               `json:"minProperties,omitempty"`
	DependentRequired map[string][]string `json:"dependentRequired,omitempty"`

	// type == number || type == integer
	Minimum          *int `json:"minimum,omitempty"`          // >=
	Maximum          *int `json:"maximum,omitempty"`          // <=
	ExclusiveMinimum *int `json:"exclusiveMinimum,omitempty"` // >
	ExclusiveMaximum *int `json:"exclusiveMaximum,omitempty"` // <
	MultipleOf       uint `json:"multipleOf,omitempty"`

	// type == array
	Items       *Property `json:"items,omitempty"` // required field
	MinItems    *uint     `json:"minItems,omitempty"`
	MaxItems    *uint     `json:"maxItems,omitempty"`
	UniqueItems bool      `json:"uniqueItems,omitempty"`
	MaxContains *uint     `json:"maxContains,omitempty"`
	MinContains *uint     `json:"minContains,omitempty"`

	// type == string
	MaxLength *uint  `json:"maxLength,omitempty"`
	MinLength *uint  `json:"minLength,omitempty"`
	Pattern   string `json:"pattern,omitempty"` // ECMA-262 regular expression

}

Property represends a map / struct entry

func From

func From(
	inputType interface{},

	baseRefPath string,

	addRef func(key string, property Property),

	hasRef func(key string) bool,

	meta *WithMeta,
) (Property, error)

From converts a struct into a value for the properties part of a json schema baseRefPath might look something like #/components/schemas/

type PropertyType

type PropertyType string

PropertyType contains the value type of a property

type Version

type Version string

Version defines the version of the schema

type WithMeta

type WithMeta struct {
	SchemaID string
}

WithMeta adds the Schema and ID field to the returned property

Jump to

Keyboard shortcuts

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