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. 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
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.31.0 -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.
The root type is named after the schema file, so schema.json gives SchemaJson.
--schema-root-type URI=TYPE names it explicitly. Each --resolve-extension is also
removed from the file name first: with --resolve-extension .schema.json,
widget.schema.json gives Widget rather than WidgetSchemaJson. The same applies to
another file a $ref points at as a whole, while a $ref to one of its definitions, such as
lib.schema.json#/definitions/Thing, names the type after the definition.
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
An empty file name, as in --schema-output=https://example.com/schema2=, writes nothing for that schema: its types
are taken to be in the package that --schema-package names, which another run writes, and the files that refer to
them import it. That run and this one must name the types alike. They do when both generate the same schemas into
the package in the same order, so give this run the package's schema files first, in the order its own run takes
them, or use --collision-strategy qualify, which names each definition after its own schema. A name collision in
such a package is reported with a reminder.
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). It is also
the name that every file generated into the package declares, so a package
generated in the same run is declared as package headerv1 where it is
imported as headerv1. 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 Go identifier other than
a keyword, _, init, main or documentation; 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:
SerializableDateSerializableTimeDuration, forformat: duration
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 |
deprecated given as a string, as schemas generated from TypeScript give it |
Marks the field or type as deprecated, as true does, with the string as the text of its Deprecated: paragraph. A value that is neither a boolean nor a string is ignored. |
fork |
Choices JSON Schema leaves open
defaultis 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: trueproperties are rejected when the input contains them, which JSON Schema allows.--disable-readonly-validationturns that off.deprecated: trueadds aDeprecated:paragraph to the doc comment of the field or type, which gopls and staticcheck report wherever it is used. JSON Schema defines the keyword from draft 2019-09; the generator reads it in every draft.- Properties a schema allows without declaring them are dropped on decode, unless the schema declares
additionalProperties. In that case anAdditionalPropertiesfield holds them. --strict-additional-properties=strictrejects undeclared properties on every object, including where the schema allows them. That is stricter than JSON Schema.--only-modelsgenerates the types without unmarshalers, so nothing is checked.- Numbers in untyped values,
interface{}fields and the values they hold, are decoded from JSON asfloat64, which loses integers beyond 2^53.--use-numberdecodes them asjson.Number, which keeps them exact, in fields and inAdditionalProperties, and writes their defaults so too. Typed fields and enum values are decoded as before, and so is YAML, since yaml.v3 decodes integers exactly.
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 and unevaluatedProperties: 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, also where a $ref points into another file. 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 becameinterface{}. The reasonno typemeans the schema has notypeand is neither a composition nor an object with properties, so its keywords, such aspattern,minimumorrequired, are checked on no value.schema fidelity: type X does not enforce all it declares: <reason>means the type kept its shape but dropped aoneOf, ananyOfwith a branch that isinterface{}, anif/then/else, anotor afalseschema. A reason such asminProperties, propertyNames not checkednames keywords that no generated code checks:contains(withminContainsandmaxContains),dependentSchemas,maxProperties,minProperties,patternProperties,propertyNames,unevaluatedItemsandunevaluatedProperties, unless--strict-additional-propertieschecks it, as described below.dependentRequiredand draft-07'sdependenciesare named where no struct of the object's own checks them, as on a type merged from a composition, or where the declared draft does not define them; where the lists of adependenciesare checked, the reason names the properties whose schemas are not, as independencies (zip) not checked. A keyword whose subschemas admit every value, such as"patternProperties": {"^x-": {}}, checks nothing and is not reported. A keyword that the draft the document declares does not define is named so, as inunevaluatedProperties (not in draft-07) not checked. A reason such asminimum beside $ref not checkednames the keywords beside a$ref, which apply from 2019-09 on, while the type generated for the$refis its target's; put them in anallOfbeside the$refinstead. A document that declares draft-07 or an earlier draft, which ignores them as well, is not warned.schema fidelity: root of F does not enforce all it declaresmeans the file F is the schemafalse, which no value meets, or has notypeand keywords that are checked only on a value of some type. Nothing is generated for it.
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. Accessors such as AsString() read the value, and constructors such as NewFooString(v) build one |
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, written inline, named by $refs or built with allOfs |
interface{} |
A struct that tries each variant, and accepts the input only when exactly one matches. A variant that a $ref names is its type. Where a variant's type cannot check its not, if/then/else or dependentSchemas, two variants could both take a valid value, so the oneOf stays interface{} |
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 |
anyOf of an object with properties and a primitive or an array |
The first branch's type: a primitive such as *string, which rejects every object, or a struct, which rejects the primitive |
interface{}, with a fidelity warning |
An anyOf on a string, a number or a boolean whose branches only check its values, such as {"type": "string", "anyOf": [{"enum": ["a", "b"]}, {"pattern": "^x-"}]} |
interface{}, and a type for each enum branch, which no field uses |
The type, such as *string |
An anyOf or oneOf whose branches only list strings, with const or enum, inline or through a $ref, such as {"anyOf": [{"$ref": "#/$defs/Alert"}, {"$ref": "#/$defs/Notice"}]} or {"oneOf": [{"const": "fast"}, {"const": "safe"}]} |
interface{}, and for an anyOf an alias of each branch's type, which no field uses |
One enum of the strings the composition admits, with a constant for each. A branch that admits only null makes the field a pointer that holds it as nil |
format: duration |
time.Duration, which encoding/json reads only from a number of nanoseconds, so a document that gives an ISO 8601 duration is rejected |
types.Duration, read and written as an ISO 8601 duration such as PT1H30M. JSON can also give a number of nanoseconds, and YAML a duration in Go's syntax, such as 1h30m, as for a time.Duration |
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{}, andadditionalItems: falselimits its length. - Draft-07
dependenciesin 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
if/then/elsekeyed on one property'sconstorenum, in anallOfor on the object itself, checks each branch'srequired, anotofrequiredand a property it narrows to some strings with aconstor anenum, written there or through a$ref, or with ananyOforoneOfof them, also where the property is optional or a nested object holds it, as described under Validation. A branch checks these whatever else it declares, and a warning names what it leaves unchecked. - An
anyOfor aoneOfwhose branches only list strings, withconstorenum, inline or through a$ref, is an enum of the strings it admits: those that a branch of theanyOflists, and those that just one branch of theoneOflists, since a string two branches list matches both. Upstream checked neither. - A
oneOforanyOfwhose branches only listrequiredchecks how many of the listed property sets an object has: exactly one for aoneOf, at least one for ananyOf. - A
notofrequiredon an object, of its own or in itsallOf, forbids properties:not: {required: [a, b]}forbids having both, andnot: {anyOf: [{required: [a]}, {required: [b]}]}having either. Upstream checked neither. dependentRequired, and the lists of properties of draft-07'sdependencies: where a property is present, the properties it lists must be too. Each is checked where the draft the document declares defines it: 2019-09 broughtdependentRequiredand droppeddependencies. A document that declares no draft has both checked, together where an object declares both.- An array type declared in
$defschecks its ownminItemsandmaxItems. - A property whose
typeadmitsnullbut whoseenumdoes not list it rejects anull. - The keywords of the values an array or a map holds are checked, at every depth:
minLength,maxLength,pattern,minimum,maximum,multipleOf,const, a nested array's ownminItemsandmaxItems, and the others a property gets. Upstream checked them on a property only. uniqueItems, which compares items as JSON, so1and1.0are equal, as are objects with the same members.- A
conston a schema that declares no type, whose value is aninterface{}. - A struct merged from an
anyOfchecks the keywords of the object theanyOfis declared on: the properties it requires, or every branch requires, and those of its own properties. Upstream checked only the branches. - A name in
requiredthat no property declares is checked: the object must have the key. Upstream checked only the names of the properties a schema declares. - An
anyOfor aoneOfon astring, a number or abooleanwhose branches only check its values, withconst,enum,pattern, a length, a bound ormultipleOf, is checked: a value must match at least one branch of theanyOf, and exactly one branch of theoneOf. Upstream checked no branch of either. A branch with aformatthat only a field's Go type checks, such asdate-time, or with apatternthat Go's regexp cannot compile, leaves the composition unchecked, with a warning. - Under
--strict-additional-properties,unevaluatedProperties: falseis checked asadditionalProperties: falseis, over the properties of the object and of itsallOfbranches, as described below. Upstream checked it nowhere.
Other differences
- A required property named
-is decoded. Upstream tagged itjson:"-", whichencoding/jsonskips. - A required array or object whose type excludes
nullis written to JSON as[]or{}when it is nil. Upstream wrotenull, which the schema rejects. - A property with a
constof a string, a number, an integer or a boolean has an exported constant, named after the struct and the field, such asConfigSchemafor a$schemaproperty. - An
integerwritten with a fraction or an exponent, such as2.0or1e2, is decoded from JSON and YAML as the integer it holds, as JSON Schema counts it. A number that holds no integer, or one that the Go type can't hold, is an error in both, and the JSON error names it as written. Upstream's code rejected2.0in JSON, asencoding/jsondoes for a Go integer, and in YAML truncated2.5to 2. - An
integer'sminimumandmaximum, and their exclusive forms, are read as the schema writes them, so a bound beyond 2^53 isn't rounded, and one with a fraction bounds the integers it lets through:maximum: 2.5lets 2 through and refuses 3. Upstream read them through afloat64, so a bound at the limit of anint64overflowed and rejected nearly every value. - Each value of an
AdditionalPropertiesfield is decoded from its own JSON or YAML, as a declared property's is: an integer exactly, and in YAML a number for a string as its text. Upstream converted the values from a decoded map, which truncated2.5to 2 for an integer and wrapped1e300. - A nested array is held to its own
minItemsandmaxItems. Upstream held each level to the property's, which rejected valid input. - A count, such as
minItemsormaxLength, written2.0or2e0is read as the integer it holds, and one that holds no integer stops generation with an error that names it. Upstream failed to load the schema.maxLength: 0andmaxItems: 0are checked, where upstream read a zero as no limit. - An
integer'smultipleOfwith a fraction is checked on the integers it allows: the multiples of 5 for2.5, and every integer for0.5. Upstream checked the multiples of 2 for2.5, and its code for a value below 1 did not compile. - An
allOfwritten inside a branch of anallOfis merged with the other branches. Upstream made itinterface{}, without a warning. - A
typeof two types withoutnull, such as["integer", "string"], keeps both: where no union wrapper holds them, it isinterface{}with a warning, as it was in a property. Upstream kept only the last type at the root, in a definition and for the values of a map, which rejected values of the first. - A schema file that is only
trueorfalseis read.truegenerates no type, as{}does, andfalseis reported, since no generated code rejects every value. Upstream failed to load either. - An
anyOfis merged on copies, so it changes none of the schemas it reads. Upstream's merge wrote into them: the branches' keywords into the properties of the object or of the first branch, and the object's type andnullinto the schemas its branches refer to. A struct's property could then take its type from another branch, a$refto a schema the merge had changed got a duplicate type, and ananyOfwhose branches had all becomenullfailed to generate. A branch that is a$refto a definition without atype, declared asinterface{}, is decoded as the type theanyOfdeclares, where upstream's code for it did not compile. A branch that admits onlynull, such as{"enum": [null]}, is theanyOf'snull, as{"type": "null"}is. - A definition declared as a pointer type, such as
type Key *stringfor"type": ["string", "null"], has noUnmarshalJSONwhere ananyOfrefers to it, since Go allows no methods on a pointer type. Upstream's code for it did not compile. - An
allOf,anyOforoneOfmember that is a$refinto a schema mapped to another Go package (--schema-package) imports that package only where a type of it is used. Upstream imported it anyway, so where the merge copied the member's fields, its code did not compile. - A property name that a struct tag can't carry for
encoding/json, such asa"b, stops generation with an error. Upstream generated a tag that decodes nothing. - A
nullwhere a schema belongs, such as an entry ofallOf, a property or a definition, stops generation with an error. Upstream crashed. - A
defaultis written as a literal of its field's Go type, or left out with a warning when no value of that type can hold it. Upstream's code for such a default did not compile. - A
patternthat Go's regexp cannot compile, such as a lookahead, is left unchecked with a warning. Upstream's check rejected every value. - A
oneOfbranch whose$refcannot be resolved is reported, as one in ananyOforallOfis. Upstream dropped it without a word. - Declarations come out in a fixed order. In upstream's output, an unrelated change could reorder them.
- A field or type whose schema sets
deprecatedhas aDeprecated:paragraph in its doc comment, as described under Choices JSON Schema leaves open. Upstream ignores the keyword. - The fidelity warnings above.
--versionprints 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.
Conformance
TestConformanceDraft7 runs the required draft-07 tests of the
JSON-Schema-Test-Suite through generated code. It
decodes each test's document into the type generated from the test's schema, as JSON and as YAML, and compares the
verdict with the suite's. The report, tests/testdata/conformance/draft7.txt,
lists every disagreement:
- a missing check accepts a document the suite marks invalid. It is silent when the generator gave no warning for the schema;
- a wrong rejection rejects a document the suite marks valid;
- a schema the generator rejects, or whose code doesn't compile, leaves its tests not run.
The suite tests one keyword at a time, mostly on schemas without a type. Real schemas rarely put such keywords on a
schema without a type: 28 of the 1,482 schemas in SchemaStore's catalog do. The disagreements fall into these
classes:
- Keywords on a schema without a
type. Such a schema becomesinterface{}, or no type at all, and nothing checks its keywords. The generator warns about them. - Objects without
type: object. A schema withpropertiesbut notypebecomes a struct, so it rejects the non-objects that the suite lets through. - YAML. yaml.v3 reads some documents differently from JSON. It decodes a number or a boolean into a string as its
text, and it can't read an escaped surrogate pair. An empty document, or one that is only
null, decodes to the zero value without an error, so its required properties aren't checked. $refforms the generator doesn't resolve. These are a base URI that an$idsets, a location-independent identifier (#foo), a URN,#itself, and a pointer intoproperties.- Property names that a Go struct tag can't hold. The generator rejects these schemas.
- Defects, such as:
type: nullon its own, which lets any value through;- a
defaultthat breaks its property's own keywords, which rejects every document that leaves the property out; - an
enumthat listsnullbeside a number, which rejectsnull.
The suite is vendored in tests/testdata/JSON-Schema-Test-Suite. To update it, run
scripts/update-test-suite.sh <commit>, then regenerate the report with OVERWRITE_EXPECTED_GO_FILE=true.
TestDifferentialFixtures does the same for the fixtures under tests/data, which combine keywords as real schemas
do. It builds documents from each fixture and from each of its top-level definitions, then mutates them one node at
a time. It compares the generated code's verdicts with those of
santhosh-tekuri/jsonschema, which passes the suite's required tests.
That validator reads a schema that declares draft-04 or draft-06 as draft-07, as the generator does. The report,
tests/testdata/differential/fixtures.txt, groups the disagreements by
schema, keyword and kind of change.
One more class shows there, by design. A struct merged from an anyOf types a property that only branches declare
after the first branch that declares it, which holds the properties the other branches declare in it as well. A
document that another branch accepts, with a value there that the first branch's schema refuses, is rejected. A
goJSONSchema type on the property sets its Go type in the struct and in the branch's own type, which drops that
branch's check of it too.
Every week, a workflow runs the same comparison over SchemaStore's schemas,
once with the generator on main and once with the latest release. It fails on a disagreement that only main has,
and on a schema that only the release generates and builds, if a second run of the schema shows it again.
Validation
- Core (RFC draft)
- Data model (§4.2.1)
-
null -
boolean -
object -
array -
number- Option to use
json.Number(--use-number, for untyped values)
- 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(for struct fields, and fields that hold a union wrapper) -
readOnly(present in the input: rejected, unless--disable-readonly-validationis set) -
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(its keywords are checked on every item, at every depth, as are those of a map's values; the draft-07 tuple form gives[]interface{}) -
maxItems -
minItems -
uniqueItems -
additionalItems(onlyfalseafter tuple-formitemsis checked, as a length limit) -
contains,minContainsandmaxContains -
unevaluatedItems
-
- Object validation (§6.5)
-
required -
properties -
additionalProperties: false(opt-in viaConfig.StrictAdditionalProperties) -
patternProperties -
dependentRequired, and the lists of properties of draft-07'sdependencies, each where the draft the document declares defines it, or where it declares none -
dependentSchemas, and the schemas of draft-07'sdependencies -
propertyNames -
maxProperties -
minProperties -
unevaluatedProperties: false(opt-in viaConfig.StrictAdditionalProperties, forallOfbranches)
-
- Conditional subschemas (§6.6) — supported as
allOfofif[const|enum]/then[/else]tagged-union dispatch on a single string discriminator property, which may be declared through a$refand may be held by nested objects, such asmeta.status; anif/then/elseon the object itself counts as one moreallOfelement; the generatedUnmarshal{JSON,YAML}peeks the discriminator and runs each branch's checks: itsrequired, anotofrequired(not: {required: [a, b]}forbids both together,not: {anyOf: [{required: [a]}, {required: [b]}]}either), and a property it narrows to some strings with aconstor anenum(then: {properties: {operator: {enum: [GT, LT]}}}), written there or through a$ref, or with ananyOforoneOfof them. Each clause compiles what it can: athenorelsethat declares other keywords as well still checks these, and a fidelity warning names the rest, as it names a clause that compiles into no check, because itsifis no such check or is keyed on another property. Athenorelsewith a$refchecks nothing, since draft-07 ignores the keywords beside a$ref, and anallOfelement that declares anything besides itsif/then/elsedeclines detection for the object. Both{const: "<V>"}and{enum: ["<V1>", "<V2>", …]}forms are recognized; the if clause must contain only the single-property check, which it may also list in itsrequired(otherrequired/composition/validation keywords decline detection). Where the discriminator, or an object holding it, is absent, an if that requires it is false, so itselseapplies, and one that does not is true, vacuously, so itsthenapplies. 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, and checks the keywords of the object it is declared on, except on a property a branch declares as well; a mix of object and non-object branches isinterface{}; branches that only listrequiredneed at least one of their property sets present; branches that only list strings, inline or through a$ref, are one enum of them) -
oneOf(primitive variants —string,number,boolean,null— become a wrapper; object variants, inline, named by a$refor built with anallOf, become a holder that dispatches on aconstdiscriminator or tries each variant; branches that only listrequiredneed exactly one of their property sets present; branches that only list strings are one enum of those that just one of them lists; note:integer-typed variants are not currently routed through the wrapper) -
not(checked as anotofrequiredon an object, in itsallOfand in a conditional'sthenorelse; any other is reported by a fidelity warning)
-
- 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(defined from draft 2019-09, checked in every draft; 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) | 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 or unevaluatedProperties: 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.
unevaluatedProperties: false, the draft 2019-09 and later way to close an object composed with allOf, rejects the
fields that neither the object nor any of its allOf branches, inline or through a $ref, declares. An anyOf, a
oneOf, an if/then/else or dependentSchemas whose subschemas declare properties evaluates them depending on the
value, and patternProperties or a branch's own additionalProperties or unevaluatedProperties evaluates properties
the struct has no field for, so there the keyword is left unchecked, with a fidelity warning. Subschemas that evaluate
no property, such as branches that only list required, change nothing, nor does a not, whose subschema must fail
and so evaluates none. So it is in a schema whose $schema names draft-07 or an
earlier draft, which doesn't have the keyword, as a validator of that draft doesn't. additionalProperties: false
beside allOf is checked over the merged properties as well, which is more lenient than JSON Schema: there it sees only
the properties declared beside it, so a validator rejects every property that the branches declare.
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.