jtd

package
v0.9.1 Latest Latest
Warning

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

Go to latest
Published: Jan 11, 2026 License: MIT Imports: 8 Imported by: 0

README

JTD to Go Generator

A JSON Type Definition (RFC 8927) to Go code generator.

Installation

go install github.com/delaneyj/toolbelt/jtd/cmd/jtd2go@latest

Usage

jtd2go -input schema.json -output types.go -package myapp
Options
  • -input: Input JTD schema file (required)
  • -output: Output Go file (default: stdout)
  • -package: Go package name (default: "types")
  • -comments: Generate comments from descriptions (default: true)
  • -validate: Generate validation methods (default: false)
  • -help: Show help

Features

Supported JTD Forms
  • Type forms: All RFC 8927 primitive types

    • booleanbool
    • stringstring
    • timestamptime.Time
    • float32, float64float32, float64
    • int8, int16, int32int8, int16, int32
    • uint8, uint16, uint32uint8, uint16, uint32
  • Enum form: String enumerations → Go constants

  • Elements form: Arrays → Go slices

  • Properties form: Objects → Go structs

  • Values form: Maps → Go maps

  • Discriminator form: Tagged unions → Go interfaces

  • Ref form: Schema references

  • Empty form: Any type → any

Additional Features
  • Nullable types using pointers
  • Optional struct fields with omitempty tags
  • Metadata descriptions as Go comments
  • Validation method generation
  • Proper handling of circular references

Examples

Simple Schema
{
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "int32" }
  }
}

Generates:

type Root struct {
    Name string `json:"name"`
    Age  int32  `json:"age"`
}
Enum Schema
{
  "definitions": {
    "status": {
      "enum": ["active", "inactive", "pending"]
    }
  }
}

Generates:

type Status string

const (
    StatusActive   Status = "active"
    StatusInactive Status = "inactive"
    StatusPending  Status = "pending"
)
Discriminated Union
{
  "definitions": {
    "shape": {
      "discriminator": "type",
      "mapping": {
        "circle": {
          "properties": {
            "radius": { "type": "float64" }
          }
        },
        "rectangle": {
          "properties": {
            "width": { "type": "float64" },
            "height": { "type": "float64" }
          }
        }
      }
    }
  }
}

Generates:

type Shape interface {
    isShape()
    Type() string
}

type ShapeCircle struct {
    Type   string  `json:"type"`
    Radius float64 `json:"radius"`
}

func (ShapeCircle) isShape() {}
func (v ShapeCircle) Type() string { return v.Type }

type ShapeRectangle struct {
    Type   string  `json:"type"`
    Width  float64 `json:"width"`
    Height float64 `json:"height"`
}

func (ShapeRectangle) isShape() {}
func (v ShapeRectangle) Type() string { return v.Type }

Testing

go test ./jtd

License

Same as the parent toolbelt project.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Generator

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

Generator generates Go code from JTD schemas

func NewGenerator

func NewGenerator(parser *Parser, opts GeneratorOptions) *Generator

NewGenerator creates a new code generator

func (*Generator) Generate

func (g *Generator) Generate() ([]byte, error)

Generate generates Go code for all schemas

func (*Generator) GenerateValidation

func (g *Generator) GenerateValidation() ([]byte, error)

GenerateValidation generates validation methods for types

func (*Generator) GenerateWithTemplate

func (g *Generator) GenerateWithTemplate() ([]byte, error)

GenerateWithTemplate generates code using a template

type GeneratorOptions

type GeneratorOptions struct {
	PackageName      string
	GenerateComments bool
	GenerateValidate bool
	TypeNamePrefix   string
	TypeNameSuffix   string
	RootTypeName     string // Name for the root schema type (defaults to package name if empty)
}

GeneratorOptions configures the code generator

type Parser

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

Parser handles parsing JTD schemas and resolving references

func NewParser

func NewParser() *Parser

NewParser creates a new JTD parser

func (*Parser) ExtractSchemas

func (p *Parser) ExtractSchemas(rootTypeName string) []SchemaInfo

ExtractSchemas extracts all schemas that need code generation

func (*Parser) GetDefinition

func (p *Parser) GetDefinition(name string) *Schema

GetDefinition returns a definition by name

func (*Parser) GetResolvedSchema

func (p *Parser) GetResolvedSchema(ref string) *Schema

GetResolvedSchema returns a resolved schema for a given reference

func (*Parser) Parse

func (p *Parser) Parse(data []byte) (*Schema, error)

Parse parses a JTD schema from JSON data

func (*Parser) ParseFile

func (p *Parser) ParseFile(filename string) (*Schema, error)

ParseFile parses a JTD schema from a file

func (*Parser) ValidateJSON

func (p *Parser) ValidateJSON(data []byte, schema *Schema) error

ValidateJSON validates JSON data against a schema

type Schema

type Schema struct {
	// Metadata
	Metadata map[string]any `json:"metadata,omitempty"`

	// Nullable indicates whether the value can be null
	Nullable bool `json:"nullable,omitempty"`

	// Type forms
	Type Type `json:"type,omitempty"`

	// Enum form
	Enum []string `json:"enum,omitempty"`

	// Elements form (for arrays)
	Elements *Schema `json:"elements,omitempty"`

	// Properties form (for objects)
	Properties           map[string]*Schema `json:"properties,omitempty"`
	OptionalProperties   map[string]*Schema `json:"optionalProperties,omitempty"`
	AdditionalProperties bool               `json:"additionalProperties,omitempty"`

	// Values form (for maps)
	Values *Schema `json:"values,omitempty"`

	// Discriminator form (for tagged unions)
	Discriminator string             `json:"discriminator,omitempty"`
	Mapping       map[string]*Schema `json:"mapping,omitempty"`

	// Ref form
	Ref string `json:"ref,omitempty"`

	// Definitions (for root schema only)
	Definitions map[string]*Schema `json:"definitions,omitempty"`
}

Schema represents a JSON Type Definition schema according to RFC 8927

func ParseSchema

func ParseSchema(data []byte) (*Schema, error)

ParseSchema parses a JSON Type Definition schema from JSON

func (*Schema) Form

func (s *Schema) Form() string

Form returns the form of the schema

func (*Schema) Validate

func (s *Schema) Validate() error

Validate checks if the schema is valid according to RFC 8927

type SchemaInfo

type SchemaInfo struct {
	Name        string
	GoName      string
	Schema      *Schema
	IsRoot      bool
	IsNullable  bool
	Description string
}

SchemaInfo contains information about a schema for code generation

type Type

type Type string

Type represents the primitive types in JTD

const (
	TypeBoolean   Type = "boolean"
	TypeString    Type = "string"
	TypeTimestamp Type = "timestamp"
	TypeFloat32   Type = "float32"
	TypeFloat64   Type = "float64"
	TypeInt8      Type = "int8"
	TypeInt16     Type = "int16"
	TypeInt32     Type = "int32"
	TypeUint8     Type = "uint8"
	TypeUint16    Type = "uint16"
	TypeUint32    Type = "uint32"
)

func (Type) IsValid

func (t Type) IsValid() bool

IsValid checks if the type is a valid JTD type

func (Type) ToGoType

func (t Type) ToGoType() string

ToGoType converts JTD type to Go type

Directories

Path Synopsis
cmd
jtd2go command

Jump to

Keyboard shortcuts

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