go-jsonschema

command module
v0.25.0-rc.8 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2026 License: MIT Imports: 10 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

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 of dependencies;
  • oneOf generated as typed wrappers and dispatching holders instead of interface{};
  • x-enum-varnames naming 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. Differences from upstream lists how its output differs, and Beyond JSON Schema what it reads and does that JSON Schema doesn't define.

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

GitHub release GitHub Workflow Status (event) Go Reference License GitHub go.mod Go version GitHub all releases GitHub commit activity

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-jsonschema on Docker Hub, or ghcr.io/plheide/go-jsonschema. Each release is tagged with its version, and only stable releases set latest, 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-jsonschema tap 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:

  • SerializableDate
  • SerializableTime

These types are needed because there is no native type provided by Go which properly handles them.

Beyond JSON Schema

The generator reads a few inputs that are not part of JSON Schema, and makes a few choices that JSON Schema leaves open. This section lists all of them, with the flags that turn them on or off. Everything else follows JSON Schema, or is listed as unsupported under Status.

Inputs that are not JSON Schema

Input Effect From
goJSONSchema On a schema, type names a Go type to use instead of generating one, imports adds the imports it needs, and nillable: true says it needs no pointer. On a property, identifier names the field, pointer makes it a pointer (true) or a value (false), and extraTags adds struct tags. upstream
x-enum-varnames Names the constants generated for an enum's values, in enum order, as OpenAPI generators read it. fork
Other x- keys Become struct tags when mapped with --extension-tag x-key=tag, and are ignored otherwise. fork, opt-in
format: int32 and format: int64 on an integer Go int32 and int64, the OpenAPI meaning of these formats, with --openapi-int-formats. Without it, an integer is an int, as upstream generates it. fork, opt-in
format: uuid Checked by --validate-formats in every draft, although JSON Schema defines it only from draft 2019-09. fork, opt-in

Choices JSON Schema leaves open

  • default is only an annotation in JSON Schema. Generated code assigns it when the key is absent from the input: to struct fields, and in the fork also to fields that hold a union wrapper.
  • readOnly: true properties are rejected when the input contains them, which JSON Schema allows. --disable-readonly-validation turns that off.
  • Properties a schema allows without declaring them are dropped on decode, unless the schema declares additionalProperties. In that case an AdditionalProperties field holds them.
  • --strict-additional-properties=strict rejects undeclared properties on every object, including where the schema allows them. That is stricter than JSON Schema.
  • --only-models generates the types without unmarshalers, so nothing is checked.

Checks that are off by default

Generated code skips these JSON Schema checks unless a flag turns them on, so its behavior stays the same as upstream's:

Check Flag
format --validate-formats, described below
additionalProperties: false --strict-additional-properties=respect-schema, described below
null where type excludes it --validate-null-types. It checks properties, the elements of arrays, and declared types that are not objects. In YAML a document that is only null is not checked, since yaml.v3 does not pass one to UnmarshalYAML.

Fidelity warnings

When generated code doesn't check something a schema declares, the generator says so on stderr, once for each type:

  • schema fidelity: type X falls back to interface{} due to <reason>; declared but not enforced: <keywords> means the type became interface{}.
  • schema fidelity: type X does not enforce all it declares: <reason> means the type kept its shape but dropped a oneOf, an if/then/else, a not or a false schema.

The keywords listed as unsupported under Validation, such as uniqueItems and patternProperties, are not reported.

Options for names, types and tags

--capitalization, --collision-strategy, --disable-custom-types-for-maps, --disable-omitempty, --disable-omitzero, --extra-imports, --min-sized-ints, --minimal-names, --struct-name-from-title, --tags and Config.AliasSingleAllOfAnyOfRefs choose how the generated code is named, typed and tagged. --collision-strategy is the fork's; the others are upstream's.

Differences from upstream

For the same schema and flags, the fork's output differs from upstream's v0.24 output as listed below. All of it is offered upstream, apart from the few changes FORK.md lists.

Types

Schema Upstream Fork
"type": ["number", "null"] type FooRate *float64, a named pointer type, which can have no methods *float64
oneOf of string, number, boolean and null variants, or "type": ["string", "number"] interface{} A struct holding one of the values, decoded by its JSON kind
oneOf of objects told apart by a const property interface{} A struct with a field per variant, decoded by that property
Any other oneOf of objects interface{} A struct that tries each variant, and accepts the input only when exactly one matches
oneOf or anyOf of a $ref, an object or an array, and {"type": "null"} interface{} for a oneOf, a copy of the schema for an anyOf A pointer to the schema's own type
An enum listing null beside values of one type, such as "enum": ["a", "b", null] A struct holding an interface{} A pointer to an enum of that type
An enum with x-enum-varnames: ["Low", "High"] Constants named after the type and the value, such as FooLevelLo Low and High
oneOf, anyOf, allOf or enum at the root No root type The root type

Schemas that only the fork generates

  • Draft-07 tuple-form items, which upstream fails to parse. The array is []interface{}, and additionalItems: false limits its length.
  • Draft-07 dependencies in the property-list form, such as {"a": ["b"]}, which upstream fails to parse inside a subschema. It is parsed, but not enforced.
  • $refs to nested definitions, such as #/definitions/a/definitions/b, in the same file or another one.

Checks the fork adds

  • An allOf of if/then/else keyed on one property's const or enum checks each branch's required, as described under Validation.
  • An array type declared in $defs checks its own minItems and maxItems.
  • A property whose type admits null but whose enum does not list it rejects a null.

Other differences

  • A required property named - is decoded. Upstream tagged it json:"-", which encoding/json skips.
  • A property name that a struct tag can't carry for encoding/json, such as a"b, stops generation with an error. Upstream generated a tag that decodes nothing.
  • Declarations come out in a fixed order. In upstream's output, an unrelated change could reorder them.
  • The fidelity warnings above.
  • --version prints the release.

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
      • 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
    • Comments (§9)
  • Validation (RFC draft)
    • Schema annotations (§10)
      • description
      • default (for struct fields, and fields that hold a union wrapper)
      • readOnly (present in the input: rejected, unless --disable-readonly-validation is set)
      • writeOnly
      • title (N/A)
      • examples (N/A)
    • 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 (the draft-07 tuple form gives []interface{})
      • maxItems
      • minItems
      • uniqueItems
      • additionalItems (only false after tuple-form items is checked, as a length limit)
      • contains
    • Object validation (§6.5)
      • required
      • properties
      • additionalProperties: false (opt-in via Config.StrictAdditionalProperties)
      • patternProperties
      • dependencies (both forms are parsed, but not enforced)
      • propertyNames
      • maxProperties
      • minProperties
    • Conditional subschemas (§6.6) — supported as allOf of if[const|enum]/then[/else] tagged-union dispatch on a single string discriminator property; the generated Unmarshal{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 (extra required/composition/validation keywords decline detection). Other conditionals are not compiled, and a fidelity warning reports them
      • if
      • then
      • else
    • Boolean subschemas (§6.7)
      • allOf (merged into one type)
      • anyOf (merged into one type that requires a match with at least one branch; a mix of object and non-object branches is interface{})
      • oneOf (primitive variants — string, number, boolean, null — become a wrapper; object variants become a holder that dispatches on a const discriminator or tries each variant; note: integer-typed variants are not currently routed through the wrapper)
      • not (reported by a fidelity warning)
    • Multi-type unions (§4.2.1) — {"type": ["string", "number", "boolean", "null"]} is wire-equivalent to a primitive oneOf and routes through the same wrapper. Same primitive set as oneOf; same integer exclusion. The ["X", "null"] shape continues to use *X for 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 to interface{}.
    • Semantic formats (§7.3)
      • Dates and times
      • Email addresses (opt-in via Config.FormatValidation)
      • Hostnames (opt-in via Config.FormatValidation)
      • IP addresses (ipv4 and ipv6, typed as net/netip.Addr)
      • Resource identifiers — uri, uri-reference (opt-in via Config.FormatValidation)
      • URI-template
      • JSON pointers
      • Regex (opt-in via Config.FormatValidation)
      • uuid (defined from draft 2019-09, checked in every draft; opt-in via Config.FormatValidation)

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) Defined by JSON Schema from draft 2019-09; checked in every draft.
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

The Go Gopher

There is no documentation for this package.

Directories

Path Synopsis
internal
pkg
schemas
Package schemas defines JSON schema types.
Package schemas defines JSON schema types.

Jump to

Keyboard shortcuts

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