jsonschema

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jan 25, 2019 License: MIT Imports: 5 Imported by: 0

README

Generate JSON Schema out of Golang schema

Usage

First install the package

go get -u github.com/naveego/go-json-schema

Then create your generator file (see Example folder)

package main

import (
	"fmt"
	"github.com/naveego/go-json-schema"
)

type Domain struct {
	Data string `json:"data"`
}

func main(){
	fmt.Println(jsonschema.NewGenerator().WithRoot(&Domain{}).MustGenerate())
}

Definitions

To include a "definitions" element in your schema, you need to pass the definitions to the generator:

package main

import (
	"fmt"
	"github.com/naveego/go-json-schema"
)

type Domain struct {
	Child Child `json:"child"`
}

type Child struct {
	Data string `json:"data"`
}

func main(){
    js, err := jsonschema.NewGenerator().
        WithRoot(&Domain{}).
        WithDefinition("child", &Child{}).
        Generate()
    if err != nil {
    	panic(err)
    }
    fmt.Println(js.String())
}

Supported tags

  • required:"true" - field will be marked as required
  • title:"Title" - title will be added
  • description:"description" - description will be added
  • extensions:"{\"enumNames\": [\"A\",\"B\",\"C\"] }" - The JSON value of the tag will be merged into the resulting schema.

On an unexported field, these tags will be added to the schema for the struct itself rather than to the property representing the field.

On string fields:
  • minLength:"5" - Set the minimum length of the value
  • maxLength:"5" - Set the maximum length of the value
  • enum:"apple|banana|pear" - Limit the available values to a defined set, separated by vertical bars
  • const:"I need to be there" - Require the field to have a specific value.
  • default:"some string value" - The default string value.
On numeric types (ints and floats)
  • min:"-4.141592" - Set a minimum value
  • max:"123456789" - Set a maximum value
  • exclusiveMin:"0" - Values must be strictly greater than this value
  • exclusiveMax:"11" - Values must be strictly smaller than this value
  • const:"42" - Property must have exactly this value.
  • default:"42" - The default numeric value.

Expected behaviour

If struct field is pointer to the primitive type, then schema will allow this type and null. E.g.:

type Domain struct {
	NullableData *string `json:"nullableData"`
}

Output

{
    "$schema": "http://json-schema.org/schema#",
    "type": "object",
    "properties": {
        "nullableData": {
            "anyOf": [
                {
                    "type": "string"
                },
                {
                    "type": "null"
                }
            ]
        }
    }
}

Documentation

Overview

Copyright Kozyrev Yury MIT license.

Index

Constants

View Source
const DEFAULT_SCHEMA = "http://json-schema.org/schema#"

Variables

This section is empty.

Functions

func Generate

func Generate(root interface{}) string

Types

type Generator

type Generator struct {
	// contains filtered or unexported fields
}

func NewGenerator

func NewGenerator(options ...Options) *Generator

func (*Generator) Generate

func (g *Generator) Generate() (*JSONSchema, error)

Generate generates a schema for the provided interface.

func (*Generator) MustGenerate

func (g *Generator) MustGenerate() *JSONSchema

func (*Generator) WithDefinition

func (g *Generator) WithDefinition(name string, d interface{}) *Generator

func (*Generator) WithDefinitions

func (g *Generator) WithDefinitions(d map[string]interface{}) *Generator

func (*Generator) WithRoot

func (g *Generator) WithRoot(r interface{}) *Generator

type JSONSchema

type JSONSchema struct {
	Schema      string              `json:"$schema,omitempty"`
	Definitions map[string]Property `json:"definitions,omitempty"`
	Property
}

func (JSONSchema) String

func (d JSONSchema) String() string

String return the JSON encoding of the JSONSchema as a string

type Options

type Options struct {
	Schema string
}

type Property

type Property struct {
	Type                 string                 `json:"type,omitempty"`
	Format               string                 `json:"format,omitempty"`
	Items                *Property              `json:"items,omitempty"`
	Properties           map[string]*Property   `json:"properties,omitempty"`
	Required             []string               `json:"required,omitempty"`
	AdditionalProperties interface{}            `json:"additionalProperties,omitempty"`
	Description          string                 `json:"description,omitempty"`
	AnyOf                []*Property            `json:"anyOf,omitempty"`
	OneOf                []*Property            `json:"oneOf,omitempty"`
	Dependencies         map[string]*Property   `json:"dependencies,omitempty"`
	Default              interface{}            `json:"default,omitempty"`
	Extensions           map[string]interface{} `json:"-"`

	// numbers validators
	MultipleOf       *float64 `json:"multipleOf,omitempty"`
	Maximum          *float64 `json:"maximum,omitempty"`
	Minimum          *float64 `json:"minimum,omitempty"`
	ExclusiveMaximum *float64 `json:"exclusiveMaximum,omitempty"`
	ExclusiveMinimum *float64 `json:"exclusiveMinimum,omitempty"`
	// string validators
	MaxLength *int64 `json:"maxLength,omitempty"`
	MinLength *int64 `json:"minLength,omitempty"`
	Pattern   string `json:"pattern,omitempty"`
	// Enum is defined for arbitrary types, but I'm currently just implementing it for strings.
	Enum  []string `json:"enum,omitempty"`
	Title string   `json:"title,omitempty"`
	// Implemented for strings and numbers
	Const interface{} `json:"const,omitempty"`
	Ref   string      `json:"$ref,omitempty"`
	// contains filtered or unexported fields
}

func (*Property) MarshalJSON added in v0.2.0

func (p *Property) MarshalJSON() ([]byte, error)

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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