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]"`
}
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:
// {
// "required": [
// "amount"
// ],
// "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.
There are a few interfaces that can be implemented on a type to customize JSON Schema generation.
Preparer
allows to change generated JSON Schema.Exposer
overrides generated JSON Schema.RawExposer
overrides generated JSON Schema.Described
exposes description.Titled
exposes title.Enum
exposes enum values.NamedEnum
exposes enum values with names.
And a few interfaces to expose subschemas (anyOf
, allOf
, oneOf
, not
and if
, then
, else
).
AnyOfExposer
exposesanyOf
subschemas.AllOfExposer
exposesallOf
subschemas.OneOfExposer
exposesoneOf
subschemas.NotExposer
exposesnot
subschema.IfExposer
exposesif
subschema.ThenExposer
exposesthen
subschema.ElseExposer
exposeselse
subschema.
Additional centralized configuration is available with
jsonschema.ReflectContext
and
Reflect
options.
CollectDefinitions
disables definitions storage in schema and calls user function instead.DefinitionsPrefix
sets path prefix for definitions.PropertyNameTag
allows using field tags other thanjson
.InterceptType
called for every type during schema reflection.InterceptProperty
called for every property during schema reflection.InlineRefs
tries to inline all references (instead of creating definitions).RootNullable
enables nullability of root schema.RootRef
converts root schema to definition reference.StripDefinitionNamePrefix
strips prefix from definition name.PropertyNameMapping
explicit name mapping instead field tags.ProcessWithoutTags
enables processing fields without any tags specified.