README
¶
[!NOTE] This is a fork of omissis/go-jsonschema. It carries generator improvements that are offered upstream as pull requests but not merged yet, among them:
- draft-07 tuple-form
items, and both forms ofdependencies;oneOfgenerated as typed wrappers and dispatching holders instead ofinterface{};x-enum-varnamesnaming the generated enum constants.Almost all of it is offered upstream; FORK.md lists the exceptions. The fork is a staging area, not a competitor.
go-jsonschema is a tool to generate Go data types from JSON Schema definitions.
This tool generates Go data types and structs that corresponds to definitions in the schema, along with unmarshalling code that validates the input JSON according to the schema's validation rules.
Badges
Installing
-
Download: Get a prebuilt binary from GitHub releases.
-
Install from source: To install with Go 1.25+:
go install github.com/plheide/go-jsonschema@latest
- Container image:
plheide/go-jsonschemaon Docker Hub, orghcr.io/plheide/go-jsonschema. Each release is tagged with its version, and only stable releases setlatest, so name a version:
docker run --rm -v "$PWD:/work" -w /work plheide/go-jsonschema:v0.25.0-rc.5 -p main schema.json
- Homebrew: the
omissis/go-jsonschematap installs upstream's releases, not this fork.
Contributing
This project makes use of go workspaces in order to ease testing of the generated code during development while keeping the codebase as tidy and maintainable as possible. It's an unusual choice, but it allows to not only test the code-generation logic, but also the generated code itself.
Usage
At its most basic:
go-jsonschema -p main schema.json
This will write a Go source file to standard output, declared under the package main.
You can generate code for multiple schemas in one run, optionally writing to different files inside different packages:
$ go-jsonschema \
--schema-package=https://example.com/schema1=github.com/myuser/myproject \
--schema-output=https://example.com/schema1=schema1.go \
--schema-package=https://example.com/schema2=github.com/myuser/myproject/stuff \
--schema-output=https://example.com/schema2=stuff/schema2.go \
schema1.json schema2.json
This will create schema1.go (declared as package myproject) and stuff/schema2.go (declared as package stuff).
If schema1.json refers to schema2.json or viceversa, the two Go files will import the other depended-on package.
Note the flag format:
--schema-package=https://example.com/schema1=github.com/myuser/myproject \
^ ^
| |
schema $id full import URL
Cross-tree $refs without network access
When a consumer schema $refs a canonical schema by its $id URL (e.g.
https://schemas.example.com/header/v1/header.schema.json), the loader will
attempt an HTTP fetch unless the URL is pre-resolved. In CI environments
behind a firewall — or when the canonical host is unreachable on principle —
this fails with dial tcp: lookup ...: no such host.
--known-schema URL=PATH pre-populates the loader cache from disk so
references to URL resolve to PATH's contents without any network attempt.
The schema is loaded for ref resolution only; no Go code is emitted for it.
$ go-jsonschema \
--known-schema=https://schemas.example.com/header/v1/header.schema.json=./vendor-schemas/header.schema.json \
--schema-package=https://schemas.example.com/header/v1/header.schema.json=example.com/lib/schemas/header/v1:headerv1 \
--schema-package=https://schemas.example.com/jobs/v1/jobs.schema.json=example.com/jobs/v1:jobsv1 \
consumer.schema.json
The :ALIAS suffix on --schema-package overrides the import alias used
in generated code (default: the package path's last segment). Set it when
two referenced packages share a last segment (e.g. both end in /v1) so
the generated file doesn't get an import v1 "..." collision. The alias
must be a valid non-keyword Go identifier; the parser splits the value on
the last colon. Library callers can set the same overrides via
generator.Config.Cache and generator.SchemaMapping.ImportAlias.
Regenerating tests' golden files
It sometimes happen that new features or bug fixes to the library require regenerating the tests' golden files, here's how to do it:
export OVERWRITE_EXPECTED_GO_FILE="true"
make test
Special types
In a few cases, special types are used to help with serializing/deserializing data frrom JSON. Namely a custom types is provided for the following semantic types:
SerializableDateSerializableTime
These types are needed because there is no native type provided by Go which properly handles them.
Status
While not finished, go-jsonschema can be used today. Aside from some minor features, only specific validations remain to be fully implemented.
Validation
- Core (RFC draft)
- Data model (§4.2.1)
-
null -
boolean -
object -
array -
number- Option to use
json.Number
- Option to use
-
string
-
- Location identifiers (§8.2.3)
- References against top-level names:
#/$defs/someName - References against nested names:
#/$defs/someName/$defs/someOtherName - References against top-level names in external files:
myschema.json#/$defs/someName - References against nested names:
myschema.json#/$defs/someName/$defs/someOtherName
- References against top-level names:
- Comments (§9)
- Data model (§4.2.1)
- Validation (RFC draft)
- Schema annotations (§10)
-
description -
default(only for struct fields) -
readOnly -
writeOnly -
(N/A)title -
(N/A)examples
-
- General validation (§6.1)
-
enum -
type(single) -
type(multiple; note: partial support, limited validation) -
const
-
- Numeric validation (§6.2)
-
multipleOf -
maximum -
exclusiveMaximum -
minimum -
exclusiveMinimum
-
- String validation (§6.3)
-
maxLength -
minLength -
pattern
-
- Array validation (§6.4)
-
items -
maxItems -
minItems -
uniqueItems -
additionalItems -
contains
-
- Object validation (§6.5)
-
required -
properties -
additionalProperties: false(opt-in viaConfig.StrictAdditionalProperties) -
patternProperties -
dependencies -
propertyNames -
maxProperties -
minProperties
-
- Conditional subschemas (§6.6) — supported as
allOfofif[const|enum]/then[/else]tagged-union dispatch on a single string discriminator property; the generatedUnmarshal{JSON,YAML}peeks the discriminator and runs each branch's required-field check. Both{const: "<V>"}and{enum: ["<V1>", "<V2>", …]}forms are recognized; the if clause must contain only the single-property check (extrarequired/composition/validation keywords decline detection)-
if -
then -
else
-
- Boolean subschemas (§6.7)
-
allOf -
anyOf -
oneOf(primitive variants only —string,number,boolean,null; note:integer-typed variants are not currently routed through the wrapper, and object discriminated unions are pending) -
not
-
- Multi-type unions (§4.2.1) —
{"type": ["string", "number", "boolean", "null"]}is wire-equivalent to a primitiveoneOfand routes through the same wrapper. Same primitive set asoneOf; sameintegerexclusion. The["X", "null"]shape continues to use*Xfor ergonomics; non-primitive types in the union (object,array) and per-value validation keywords on the union (format,minimum, etc.) decline detection and fall back tointerface{}. - Semantic formats (§7.3)
- Dates and times
- Email addresses (opt-in via
Config.FormatValidation) - Hostnames (opt-in via
Config.FormatValidation) - IP addresses (
ipv4andipv6, typed asnet/netip.Addr) - Resource identifiers —
uri,uri-reference(opt-in viaConfig.FormatValidation) - URI-template
- JSON pointers
- Regex (opt-in via
Config.FormatValidation) -
uuid(extension; opt-in viaConfig.FormatValidation)
- Schema annotations (§10)
Opt-in format validation
Setting Config.FormatValidation.Enabled = true emits a runtime check on
every format keyword listed below, including strings held in arrays and
maps (nested ones too); the error then names the element, as in ids[1] or
byName["a"]. The validator runs after the typed struct decode, so the
field's Go type is already its target form. Optional pointer fields are
skipped when nil, so absent values do not trigger validation.
format |
Strategy | Notes |
|---|---|---|
uuid |
RE2 regex against the canonical 8-4-4-4-12 hex form (case-insensitive) | Not in the JSON Schema core spec; supported as a common extension. |
email |
net/mail.ParseAddress + reject if a display-name is present + require the parsed address to round-trip the input verbatim |
Stricter than the Go stdlib default: only RFC 5321 addr-spec (local@domain) is accepted. Forms like Alice <alice@example.com> or <bob@example.com> are rejected. |
uri |
net/url.Parse + IsAbs() + RFC 3986 character-class regex |
Rejects whitespace, control characters, and malformed percent-encoding (% not followed by two hex digits). Empty strings are rejected (not absolute). |
uri-reference |
net/url.Parse + RFC 3986 character-class regex |
Same character-class check as uri. Empty strings, fragment-only refs (#x), and relative paths (/a/b) are accepted per RFC 3986. |
hostname |
RE2 regex (RFC 1123 labels) | |
regex |
regexp.Compile (Go's RE2 syntax) |
The validation is opt-in to preserve existing behavior. To restrict
validation to a subset of keywords, set Config.FormatValidation.AllowList:
cfg.FormatValidation = generator.FormatValidationConfig{
Enabled: true,
AllowList: []string{"uuid", "email"}, // nil = all known formats
}
From the CLI, use --validate-formats:
# Validate every supported format keyword.
go-jsonschema --validate-formats=all -p main schema.json
# Validate only specific formats.
go-jsonschema --validate-formats=uuid,email -p main schema.json
# Explicit off (same as omitting the flag).
go-jsonschema --validate-formats=off -p main schema.json
Unknown format names are rejected at flag-parse time so a typo like
uuid,emial fails immediately rather than silently disabling email
validation.
The uri / uri-reference validation is best-effort, not RFC-3986-perfect —
no Go validator (stdlib or third-party) is — but it catches the common
cases that bare url.Parse accepts (whitespace, control chars, malformed
pct-encoding).
Opt-in additionalProperties: false enforcement
Config.StrictAdditionalProperties controls whether unknown fields in JSON
or YAML input are rejected at unmarshal time. The three modes are:
| Mode | Behavior |
|---|---|
"" (off, default) |
Silently drop unknown fields. Preserves historical behavior. |
"respect-schema" |
Reject unknown fields only for objects whose schema declares additionalProperties: false. Other objects continue to drop unknown fields silently. |
"strict" |
Reject unknown fields for every generated object type, regardless of what the schema declared. Skipped when the schema specifies a typed additionalProperties (a catch-all map field is generated instead). |
Enforcement runs against the raw decoded map, so JSON and YAML inputs are
checked uniformly. patternProperties schemas suppress enforcement with a
warning, since the generator has no first-class support for them yet.
cfg.StrictAdditionalProperties = generator.StrictAdditionalPropertiesRespectSchema
From the CLI, use --strict-additional-properties:
# Respect the schema's additionalProperties: false declarations.
go-jsonschema --strict-additional-properties=respect-schema -p main schema.json
# Reject unknown fields for every object type.
go-jsonschema --strict-additional-properties=strict -p main schema.json
# Explicit off (same as omitting the flag).
go-jsonschema --strict-additional-properties=off -p main schema.json
Unknown mode names (e.g. --strict-additional-properties=rstrict) are
rejected at flag-parse time so a typo cannot silently fall back to "off".
License
MIT license. See LICENSE file.
Documentation
¶
There is no documentation for this package.