This library provides Go structures to marshal/unmarshal and reflect JSON Schema documents.
type MyStruct struct {
Amount float64 `json:"amount" minimum:"10.5" example:"20.6" required:"true"`
Abc string `json:"abc" pattern:"[abc]"`
_ struct{} `additionalProperties:"false"` // Tags of unnamed field are applied to parent schema.
_ struct{} `title:"My Struct" description:"Holds my data."` // Multiple unnamed fields can be used.
}
reflector := jsonschema.Reflector{}
schema, err := reflector.Reflect(MyStruct{})
if err != nil {
log.Fatal(err)
}
j, err := json.MarshalIndent(schema, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(j))
// Output:
// {
// "title": "My Struct",
// "description": "Holds my data.",
// "required": [
// "amount"
// ],
// "additionalProperties": false,
// "properties": {
// "abc": {
// "pattern": "[abc]",
// "type": "string"
// },
// "amount": {
// "examples": [
// 20.6
// ],
// "minimum": 10.5,
// "type": "number"
// }
// },
// "type": "object"
// }By default, JSON Schema is generated from Go struct field types and tags. It works well for the majority of cases, but if it does not there are rich customization options.
type MyObj struct {
BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
}Note: field tags are only applied to inline schemas, if you use named type then referenced schema
will be created and tags will be ignored. This happens because referenced schema can be used in
multiple fields with conflicting tags, therefore customization of referenced schema has to done on
the type itself via RawExposer, Exposer or Preparer.
Each tag value has to be put in double quotes ("123").
These tags can be used:
title, stringdescription, stringdefault, can be scalar or JSON valueexample, a scalar value that matches type of parent property, for an array it is applied to itemsexamples, a JSON array valueconst, can be scalar or JSON valuepattern, stringformat, stringmultipleOf, float > 0maximum, floatminimum, floatmaxLength, integerminLength, integermaxItems, integerminItems, integermaxProperties, integerminProperties, integerexclusiveMaximum, booleanexclusiveMinimum, booleanuniqueItems, booleanenum, tag value must be a JSON or comma-separated list of stringsrequired, boolean, marks property as required
Unnamed fields can be used to configure parent schema:
type MyObj struct {
BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
_ struct{} `additionalProperties:"false" description:"MyObj is my object."`
}In case of a structure with multiple name tags, you can enable filtering of unnamed fields with ReflectContext.UnnamedFieldWithTag option and add matching name tags to structure (e.g. query:"_").
type MyObj struct {
BoundedNumber int `query:"boundedNumber" minimum:"-100" maximum:"100"`
SpecialString string `json:"specialString" pattern:"^[a-z]{4}$" minLength:"4" maxLength:"4"`
// These parent schema tags would only be applied to `query` schema reflection (not for `json`).
_ struct{} `query:"_" additionalProperties:"false" description:"MyObj is my object."`
}There are a few interfaces that can be implemented on a type to customize JSON Schema generation.
Preparerallows to change generated JSON Schema.Exposeroverrides generated JSON Schema.RawExposeroverrides generated JSON Schema.Describedexposes description.Titledexposes title.Enumexposes enum values.NamedEnumexposes enum values with names.
And a few interfaces to expose subschemas (anyOf, allOf, oneOf, not and if, then, else).
AnyOfExposerexposesanyOfsubschemas.AllOfExposerexposesallOfsubschemas.OneOfExposerexposesoneOfsubschemas.NotExposerexposesnotsubschema.IfExposerexposesifsubschema.ThenExposerexposesthensubschema.ElseExposerexposeselsesubschema.
There are also helper functions
jsonschema.AllOf,
jsonschema.AnyOf,
jsonschema.OneOf
to create exposer instance from multiple values.
Additional centralized configuration is available with
jsonschema.ReflectContext and
Reflect options.
CollectDefinitionsdisables definitions storage in schema and calls user function instead.DefinitionsPrefixsets path prefix for definitions.PropertyNameTagallows using field tags other thanjson.InterceptTypecalled for every type during schema reflection.InterceptPropertycalled for every property during schema reflection.InlineRefstries to inline all references (instead of creating definitions).RootNullableenables nullability of root schema.RootRefconverts root schema to definition reference.StripDefinitionNamePrefixstrips prefix from definition name.PropertyNameMappingexplicit name mapping instead field tags.ProcessWithoutTagsenables processing fields without any tags specified.