jsonschema
Generate JSON Schema 2020-12 documents from Go types using reflection, struct tags, and doc comments.
Repository Health
Technical Analysis
jsonschema is a Go library that reflects over your existing struct types to produce JSON Schema documents conforming to the 2020-12 draft, eliminating the need to hand-write and keep schema files in sync with your Go code. It reads json and jsonschema struct tags to infer property names, required fields, and validation constraints (string length, numeric ranges, patterns, enums), and can pull field descriptions directly from Go doc comments via AddGoComments.
Originally forked from alecthomas/jsonschema, the library is maintained by Invopop, where it underpins their GOBL open business library, and has been extended with configurable Reflector options — custom ID/anchor bases, key-naming strategies for snake_case output, $defs-based or inlined definitions, and hook interfaces (JSONSchema(), JSONSchemaExtend(), JSONSchemaAlias()) for types that need custom-authored or JSON-marshal-aware schemas.
What You Get
- A
Reflect()/ReflectFromType()entrypoint that turns any Go value or type into a*jsonschema.Schemastruct, ready to marshal to JSON - Support for
jsonandjsonschemastruct tags covering minLength/maxLength, pattern, format, enum, min/max, required, and custom extras - A
Reflectorwith configurable options:KeyNamer,Namer,Lookup,Mapper,BaseSchemaID,DoNotReference, andAllowAdditionalProperties AddGoComments()to pull field and type descriptions directly from your existing Go doc comments instead of duplicating them in tags- Custom schema hooks —
JSONSchema(),JSONSchemaExtend(),JSONSchemaAlias(),JSONSchemaProperty()— for types with hand-rolled or JSON Marshal/Unmarshal-aware behavior
Common Use Cases
- API contract generation - a Go backend team generates a JSON Schema for its request/response types and publishes it alongside API docs so client SDKs and frontend validators stay in sync with the Go source of truth
- Config file validation - a CLI tool author reflects its Go config struct into a schema and ships it for editor autocompletion and validation of YAML/JSON config files
- Business document validation - Invopop uses the library internally in GOBL to derive schemas for structured business documents (invoices, tax records) directly from Go types
- Multi-service schema sharing - a team defines shared data types once in Go and reflects them into schema files consumed by non-Go services for cross-language validation
Under The Hood
Architecture
The core is a recursive dispatcher, reflectTypeToSchema in reflect.go, which type-switches on reflect.Kind (struct, slice/array, map, interface, numeric, bool, string) and delegates to focused helpers like reflectStruct, reflectSliceOrArray, and reflectMap. Before falling into that switch it checks a chain of extension points in order — a Mapper override, a customSchemaImpl/JSONSchema() hook, an aliasSchemaImpl/JSONSchemaAlias() redirect — so callers can intercept generation for any type without forking the library. Struct field handling (reflectStructFields) separately resolves JSON tag names, omitempty/omitzero-derived requiredness, and jsonschema tag constraints via structKeywordsFromTags, while addDefinition/refDefinition manage the $defs map and $ref reuse so recursive or repeated types are only defined once. A parallel file, reflect_comments.go, adds an independent go/parser+go/doc-based comment extractor that populates a CommentMap consulted during struct-field reflection — cleanly decoupled from the core reflection path.
Tech Stack
The module targets Go 1.24 and keeps its non-test dependency surface small: github.com/pb33f/ordered-map/v2 backs the Schema.Properties field so that generated property order matches struct field order (plain Go maps would randomize it), pulling in bahlo/generic-list-go and buger/jsonparser transitively. Testing relies on stretchr/testify for assertions. Comment extraction uses only the Go standard library (go/ast, go/doc, go/parser, go/token), and schema numeric fields use encoding/json.Number to avoid float-precision loss when round-tripping constraints like maximum/minimum.
Code Quality
The repo carries three dedicated test files (reflect_test.go, id_test.go, reflect_comments_test.go) with roughly two dozen Test* functions plus a reflect_fuzz_test.go fuzz target exercising the reflector against arbitrary struct shapes, run in CI via a golangci-lint GitHub Actions workflow. The .golangci.yml config enables an extensive linter set (gocritic, gocyclo, revive, unconvert, unparam, dupl, goconst, nakedret), signaling active enforcement of style and complexity limits beyond the Go compiler’s defaults. Field-level constraint parsing (genericKeywords) is dense and marked //nolint:gocyclo, an honest acknowledgment of its complexity rather than a silent suppression.
API Design
The public surface is deliberately small: package-level Reflect(v)/ReflectFromType(t) cover the common case with zero configuration, while a Reflector struct with exported fields (not a builder pattern) exposes every knob — base schema ID, key/type naming, additional-properties behavior, definition inlining — as simple field assignment. Extension is interface-based rather than requiring subclassing or wrapper types: any struct can opt into JSONSchema(), JSONSchemaExtend(), JSONSchemaAlias(), or JSONSchemaProperty() to customize its own schema output, which keeps customization co-located with the type it affects rather than scattered across reflector configuration.
Used by 9 apps in this directory
Coder
Devops · Developer Tools · Code Editors
Self-hosted cloud development environments and AI coding agents — defined in Terraform, connected via WireGuard, automatically shut down when idle.
Crush
Developer Tools · AI Code Assistants · AI Assistants
Your terminal coding companion — wire up any LLM with LSP intelligence, MCP extensibility, and a skills system that learns your workflow.
CubeSandbox
Developer Tools · Security · AI Agents
Instant, concurrent, hardware-isolated MicroVM sandboxes for AI agents — E2B-API compatible, sub-60ms cold starts, and a built-in zero-trust egress proxy, all self-hostable at scale.
Digger
Devops · Automation · Developer Tools
Run Terraform and OpenTofu natively inside your existing CI pipeline — no separate runners, no third-party secrets, no extra compute costs.
ezBookkeeping
Invoicing Finance
Lightweight self-hosted personal finance manager with AI receipt scanning, multi-currency support, and MCP integration for complete data privacy.
Glasskube
Developer Tools · Devops
A next-generation Kubernetes package manager with a GUI, CLI, and native GitOps integration that makes deploying cluster workloads 20x faster than Helm.
Hanko
Security · Authentication
Open source, self-hostable authentication platform with passkeys, SAML SSO, and OAuth — the privacy-first alternative to Auth0 and Clerk.
iii
Developer Tools · Devops
Compose, extend, and observe every backend service in real time using three primitives: Workers, Functions, and Triggers.
Formance Ledger
Invoicing Finance · Developer Tools · Databases
The programmable open source core ledger for fintech — build money-moving applications with atomic multi-posting transactions, account-based modeling, and Numscript, a built-in DSL for financial logic.