generate

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2024 License: MIT Imports: 11 Imported by: 0

README

generate

Generates Go (golang) Structs from JSON schema.

Requirements

  • Go 1.22+

Usage

Install

$ go install github.com/Graff913/generate-go-json-schema/cmd/schema-generate

or

Build

$ make

Run

$ schema-generate exampleschema.json

Example

This schema

{
  "$schema": "http://json-schema.org/draft-04/schema#",
  "title": "Example",
  "id": "http://example.com/exampleschema.json",
  "type": "object",
  "description": "An example JSON Schema",
  "properties": {
    "name": {
      "type": "string"
    },
    "address": {
      "$ref": "#/$defs/address"
    },
    "status": {
      "$ref": "#/$defs/status"
    }
  },
  "$defs": {
    "address": {
      "id": "address",
      "type": "object",
      "description": "Address",
      "properties": {
        "street": {
          "type": "string",
          "description": "Address 1",
          "maxLength": 40
        },
        "houseNumber": {
          "type": "integer",
          "description": "House Number"
        }
      }
    },
    "status": {
      "type": "object",
      "properties": {
        "favouriteCat": {
          "enum": [
            "A",
            "B",
            "C"
          ],
          "type": "string",
          "description": "The favourite cat.",
          "maxLength": 1
        }
      }
    }
  }
}

generates

package main

// Address Address
type Address struct {

	// House Number
	HouseNumber *int `json:"houseNumber,omitempty"`

	// Address 1
	Street *string `json:"street,omitempty"`
}

// Example An example JSON Schema
type Example struct {
	Address *Address `json:"address,omitempty"`
	Name *string `json:"name,omitempty"`
	Status *Status `json:"status,omitempty"`
}

// FavouriteCat The favourite cat.
type FavouriteCat string

const (
	FavouriteCatA FavouriteCat = "A"
	FavouriteCatB FavouriteCat = "B"
	FavouriteCatC FavouriteCat = "C"
)

// Status 
type Status struct {

	// The favourite cat.
	FavouriteCat FavouriteCat `json:"favouriteCat,omitempty"`
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Output

func Output(w io.Writer, g *Generator, pkg string, bson bool, tagOmitempty bool)

Output generates code and writes to w.

Types

type AdditionalProperties

type AdditionalProperties Schema

AdditionalProperties handles additional properties present in the JSON schema.

func (*AdditionalProperties) UnmarshalJSON

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

UnmarshalJSON handles unmarshalling AdditionalProperties from JSON.

type AnalysisFile added in v1.2.0

type AnalysisFile struct {
	Root bool
	Path string
}

func AnalysisFiles added in v1.2.0

func AnalysisFiles(rootPath string, inputFiles []string) ([]AnalysisFile, error)

type Enum

type Enum struct {
	Name  string
	Const string
}

type Field

type Field struct {
	// The golang name, e.g. "Address1"
	Name string
	// The JSON name, e.g. "address1"
	JSONName string
	// The golang type of the field, e.g. a built-in type like "string" or the name of a struct generated
	// from the JSON schema.
	Type string
	// Required is set to true when the field is required.
	Required    bool
	Description string
}

Field defines the data required to generate a field in Go.

type Func

type Func struct {
	Name      string
	NameTypes []string
}

type Generator

type Generator struct {
	Structs map[string]Struct
	Aliases map[string]Field
	// contains filtered or unexported fields
}

Generator will produce structs from the JSON schema.

func New

func New(schemas ...*Schema) *Generator

New creates an instance of a generator which will produce structs.

func (*Generator) CreateTypes

func (g *Generator) CreateTypes(rootPath, pkg string, bson bool) (err error)

CreateTypes creates types from the JSON schemas, keyed by the golang name.

type RefResolver

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

RefResolver allows references to be resolved.

func NewRefResolver

func NewRefResolver(schemas []*Schema) *RefResolver

NewRefResolver creates a reference resolver.

func (*RefResolver) GetPath

func (r *RefResolver) GetPath(schema *Schema) string

GetPath generates a path to given schema.

func (*RefResolver) GetSchemaByReference

func (r *RefResolver) GetSchemaByReference(rootPath string, schema *Schema) (*Schema, error)

GetSchemaByReference returns the schema.

func (*RefResolver) Init

func (r *RefResolver) Init() error

Init the resolver.

func (*RefResolver) InsertURI

func (r *RefResolver) InsertURI(uri string, schema *Schema) error

InsertURI to the references.

type Schema

type Schema struct {
	// SchemaType identifies the schema version.
	// http://json-schema.org/draft-07/json-schema-core.html#rfc.section.7
	SchemaType string `json:"$schema"`

	// ID{04,06} is the schema URI identifier.
	// http://json-schema.org/draft-07/json-schema-core.html#rfc.section.8.2
	ID04 string `json:"id"`  // up to draft-04
	ID06 string `json:"$id"` // from draft-06 onwards

	// Title and Description state the intent of the schema.
	Title       string
	Description string

	Root bool

	// TypeValue is the schema instance type.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.1.1
	TypeValue   interface{} `json:"type"`
	FormatValue interface{} `json:"format"`
	EnumValue   []string    `json:"enum"`
	Deprecated  bool        `json:"deprecated"`

	// Definitions are inline re-usable schemas.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.9
	Definitions map[string]*Schema `json:"$defs"`

	// Properties, Required and AdditionalProperties describe an object's child instances.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.5
	Properties map[string]*Schema
	Required   []string

	// "additionalProperties": {...}
	AdditionalProperties *AdditionalProperties

	// "additionalProperties": false
	AdditionalPropertiesBool *bool `json:"-"`

	AnyOf []*Schema
	AllOf []*Schema
	OneOf []*Schema

	// Default can be used to supply a default JSON value associated with a particular schema.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.10.2
	Default interface{}

	// Examples ...
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.10.4
	Examples []interface{}

	// Reference is a URI reference to a schema.
	// http://json-schema.org/draft-07/json-schema-core.html#rfc.section.8
	Reference string `json:"$ref"`

	// Items represents the types that are permitted in the array.
	// http://json-schema.org/draft-07/json-schema-validation.html#rfc.section.6.4
	Items *Schema

	// NameCount is the number of times the instance name was encountered across the schema.
	NameCount int `json:"-" `

	// Parent schema
	Parent *Schema `json:"-" `

	// Key of this schema i.e. { "JSONKey": { "type": "object", ....
	JSONKey string `json:"-" `

	// path element - for creating a path by traversing back to the root element
	PathElement string `json:"-"`

	// calculated struct name of this object, cached here
	GeneratedType string `json:"-"`
}

Schema represents JSON schema.

func Parse

func Parse(schema string, uri *url.URL) (*Schema, error)

Parse parses a JSON schema from a string.

func ParseWithSchemaKeyRequired

func ParseWithSchemaKeyRequired(schema string, uri *url.URL, schemaKeyRequired bool) (*Schema, error)

ParseWithSchemaKeyRequired parses a JSON schema from a string with a flag to set whether the schema key is required.

func ReadInputFiles

func ReadInputFiles(inputFiles []AnalysisFile, schemaKeyRequired bool) ([]*Schema, error)

ReadInputFiles from disk and convert to JSON schema.

func (*Schema) FixMissingTypeValue

func (schema *Schema) FixMissingTypeValue()

FixMissingTypeValue is backwards compatible, guessing the users intention when they didn't specify a type.

func (*Schema) GetRoot

func (schema *Schema) GetRoot() *Schema

GetRoot returns the root schema.

func (*Schema) ID

func (schema *Schema) ID() string

ID returns the schema URI id.

func (*Schema) Init

func (schema *Schema) Init()

Init schema.

func (*Schema) IsRoot

func (schema *Schema) IsRoot() bool

IsRoot returns true when the schema is the root.

func (*Schema) MultiType

func (schema *Schema) MultiType() (types []string, isMultiType bool, pointer bool)

MultiType returns "type" as an array

type Struct

type Struct struct {
	// The ID within the JSON schema, e.g. #/$defs/address
	ID string
	// The golang name, e.g. "Address"
	Name string
	// Description of the struct
	Description string
	Fields      map[string]Field

	Func Func

	Enums []Enum

	GenerateCode   bool
	AdditionalType string
}

Struct defines the data required to generate a struct in Go.

Directories

Path Synopsis
cmd
schema-generate
The schema-generate binary reads the JSON schema files passed as arguments and outputs the corresponding Go structs.
The schema-generate binary reads the JSON schema files passed as arguments and outputs the corresponding Go structs.

Jump to

Keyboard shortcuts

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