jsonschema

package module
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 2, 2023 License: MIT Imports: 5 Imported by: 0

README

go-jsonschema

Go Report Card Go Reference Go version GitHub release (latest SemVer)

A JSON schema code generator for Go, supporting draft 2020-12, supporting reference resolving between multiple schema files.

This module is a fork of git.sr.ht/~emersion/go-jsonschema, with the following improvement:

  • Support stdin and stdout for input and output.
  • Support multiple schema files. Will resolve references between files correctly.
  • Support base local directory for resolving relative references, and base URI for resolving downloaded references.
  • Support special uppercase field names, such as ID and URL.
  • Support additional properties and pattern properties.

For the above features, we introduce some breaking changes, so I publish this module instead of raising a PR.

Installation

go install github.com/RyoJerryYu/go-jsonschema/cmd/jsonschemagen

Usage

jsonschemagen -s <schema> -o <output>

Or, with the support of stdin/stdout and multiple schema files:

find schema -name '*.json' | xargs jsonschemagen --rootdir=$PWD -n structs -u id -u url > out/generated.go

Full usage:

Generate Go types and helpers for the specified JSON schema.
If no schema file is specified or specified to "-", read from stdin.

Usage:
  jsonschemagen [flags] [schema file]...

Examples:
$ find schema -name '*.json' | xargs jsonschemagen --rootdir=$PWD -n out > out/generated.go

Flags:
      --baseuri string                 base URI
  -h, --help                           help for jsonschemagen
  -o, --output string                  The output filename.
                                       If not provided or specified to "-", output to stdout.
  -n, --packagename string             package name
      --rootdir string                 root directory
  -s, --schema string                  The schema filename, deprecated.
                                       recommended to use positional argument.
                                       "-" for stdin.
  -u, --upper-property-names strings   Apply full upper case to the property names.
                                       e.g. given "id", "Id" or "ID" as flags, when a type or field name 
                                       parsed as "Id", would be converted as "ID"
      --with-additional-properties     Generate additional properties and pattern properties

One Go type per definition will be generated.

  • int64 is used for "type": "integer".
  • json.Number is used for "type": "number".
  • schemas with "type": ["null", <other>] and {"oneOf": [{"type": "null"}, <other>]} are considered as optional, will be generated as *<other>.
  • Resolvable references are generated as the corresponding Go type. Non-resolvable references are generated as json.RawMessage.
  • Additional properties and pattern properties are not generated by default. Use --with-additional-properties to generate them as map[string]json.RawMessage .

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AdditionalProperties

type AdditionalProperties struct {
	*Schema
	// contains filtered or unexported fields
}

func AdditionalPropertiesBool

func AdditionalPropertiesBool(b bool) AdditionalProperties

func (*AdditionalProperties) HaveAdditionalProperties

func (ap *AdditionalProperties) HaveAdditionalProperties() bool

func (*AdditionalProperties) IsFalse

func (ap *AdditionalProperties) IsFalse() bool

func (*AdditionalProperties) IsSchema

func (ap *AdditionalProperties) IsSchema() bool

func (*AdditionalProperties) MarshalJSON

func (ap *AdditionalProperties) MarshalJSON() ([]byte, error)

func (*AdditionalProperties) NoAdditionalProperties

func (ap *AdditionalProperties) NoAdditionalProperties() bool

func (*AdditionalProperties) UnmarshalJSON

func (ap *AdditionalProperties) UnmarshalJSON(b []byte) error

type Schema

type Schema struct {
	// Core
	Schema     string             `json:"$schema"`
	Vocabulary map[string]bool    `json:"$vocabulary"`
	ID         string             `json:"$id"`
	Ref        string             `json:"$ref"`
	DynamicRef string             `json:"$dynamicRef"`
	Defs       map[string]*Schema `json:"$defs"`
	Comment    string             `json:"$comment"`

	// Applying subschemas with logic
	AllOf []Schema `json:"allOf"`
	AnyOf []Schema `json:"anyOf"`
	OneOf []Schema `json:"oneOf"`
	Not   []Schema `json:"not"`

	// Applying subschemas conditionally
	If               *Schema           `json:"if"`
	Then             *Schema           `json:"then"`
	Else             *Schema           `json:"else"`
	DependentSchemas map[string]Schema `json:"dependentSchemas"`

	// Applying subschemas to arrays
	PrefixItems []Schema `json:"prefixItems"`
	Items       *Schema  `json:"items"`
	Contains    *Schema  `json:"contains"`

	// Applying subschemas to objects
	Properties           map[string]*Schema    `json:"properties"`
	PatternProperties    map[string]*Schema    `json:"patternProperties"`
	AdditionalProperties *AdditionalProperties `json:"additionalProperties"`
	PropertyNames        *Schema               `json:"propertyNames"`

	// Validation
	Type  TypeSet       `json:"type"`
	Enum  []interface{} `json:"enum"`
	Const interface{}   `json:"const"`

	// Validation for numbers
	MultipleOf       json.Number `json:"multipleOf"`
	Maximum          json.Number `json:"maximum"`
	ExclusiveMaximum json.Number `json:"exclusiveMaximum"`
	Minimum          json.Number `json:"minimum"`
	ExclusiveMinimum json.Number `json:"exclusiveMinimum"`

	// Validation for strings
	MaxLength int    `json:"maxLength"`
	MinLength int    `json:"minLength"`
	Pattern   string `json:"pattern"`

	// Validation for arrays
	MaxItems    int  `json:"maxItems"`
	MinItems    int  `json:"minItems"`
	UniqueItems bool `json:"uniqueItems"`
	MaxContains int  `json:"maxContains"`
	MinContains int  `json:"minContains"`

	// Validation for objects
	MaxProperties     int                 `json:"maxProperties"`
	MinProperties     int                 `json:"minProperties"`
	Required          []string            `json:"required"`
	DependentRequired map[string][]string `json:"dependentRequired"`

	// Basic metadata annotations
	Title       string        `json:"title"`
	Description string        `json:"description"`
	Default     interface{}   `json:"default"`
	Deprecated  bool          `json:"deprecated"`
	ReadOnly    bool          `json:"readOnly"`
	WriteOnly   bool          `json:"writeOnly"`
	Examples    []interface{} `json:"examples"`
}

func LoadSchema

func LoadSchema(in io.Reader, fileUri *url.URL) *Schema

LoadSchema loads a schema from a JSON file. if input schema does not have $id, it will be set to the file URI.

func (*Schema) IsRequired

func (schema *Schema) IsRequired(propName string) bool

func (*Schema) NoAdditionalProps

func (schema *Schema) NoAdditionalProps() bool

func (*Schema) SchemaType

func (schema *Schema) SchemaType() Type

func (*Schema) SinglePatternProp

func (schema *Schema) SinglePatternProp() *Schema

func (*Schema) UnmarshalJSON

func (schema *Schema) UnmarshalJSON(b []byte) error

func (*Schema) UnwrapNullableSchema

func (schema *Schema) UnwrapNullableSchema() (*Schema, bool)

UnwrapNullableSchema unwraps a schema in the form:

{
	"oneOf": {
		{ "type": "null" },
		<sub-schema>
	}
}

or

{
	"type": ["null", <sub-type>]
}

type Type

type Type string
const (
	TypeNull    Type = "null"
	TypeBoolean Type = "boolean"
	TypeObject  Type = "object"
	TypeArray   Type = "array"
	TypeNumber  Type = "number"
	TypeString  Type = "string"
	TypeInteger Type = "integer"
)

type TypeSet

type TypeSet []Type

func (*TypeSet) UnmarshalJSON

func (ts *TypeSet) UnmarshalJSON(b []byte) error

Directories

Path Synopsis
cmd

Jump to

Keyboard shortcuts

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