Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
J

jsonschema-go

> 编程语言
Open source

JSON Schema mapping for Go

188 stars0 likes2 views
WebsiteGitHub

About

JSON Schema mapping for Go

JSON Schema structures for Go

This library provides Go structures to marshal/unmarshal and reflect JSON Schema documents.

Reflector

Documentation.

…

Customization

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.

Field tags

go
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, string
  • description, string
  • default, can be scalar or JSON value
  • example, a scalar value that matches type of parent property, for an array it is applied to items
  • examples, a JSON array value
  • const, can be scalar or JSON value
  • deprecated, boolean
  • readOnly, boolean
  • writeOnly, boolean
  • pattern, string
  • format, string
  • multipleOf, float > 0
  • maximum, float
  • minimum, float
  • maxLength, integer
  • minLength, integer
  • maxItems, integer
  • minItems, integer
  • maxProperties, integer
  • minProperties, integer
  • exclusiveMaximum, boolean
  • exclusiveMinimum, boolean
  • uniqueItems, boolean
  • enum, tag value must be a JSON or comma-separated list of strings
  • required, boolean, marks property as required
  • nullable, boolean, overrides nullability of the property

Unnamed fields can be used to configure parent schema:

go
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:"_").

go
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."`
}

Complex nested maps and slices/arrays can be configured with path-prefixed field tags.

go
type MyObj struct {
	Ints          []int            `json:"ints" items.title:"My int"`
	ExtraFloats   [][]float64      `json:"extra_floats" items.items.title:"My float" items.items.enum:"1.23,4.56"`
	MappedStrings map[int]string   `json:"mapped_strings" additionalProperties.enum:"abc,def"`
	VeryDeep      map[int][]string `json:"very_deep" additionalProperties.items.enum:"abc,def"`
}

Implementing interfaces on a type

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.
  • SchemaInliner inlines schema without creating a definition.
  • IgnoreTypeName, when implemented on a mapped type forces the use of original type for definition name.
  • EmbedReferencer, when implemented on an embedded field type, makes an allOf reference to that type definition.

And a few interfaces to expose subschemas (anyOf, allOf, oneOf, not and if, then, else).

  • AnyOfExposer exposes anyOf subschemas.
  • AllOfExposer exposes allOf subschemas.
  • OneOfExposer exposes oneOf subschemas.
  • NotExposer exposes not subschema.
  • IfExposer exposes if subschema.
  • ThenExposer exposes then subschema.
  • ElseExposer exposes else subschema.

There are also helper functions jsonschema.AllOf, jsonschema.AnyOf, jsonschema.OneOf to create exposer instance from multiple values.

Configuring the reflector

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 than json.
  • InterceptSchema called for every type during schema reflection.
  • InterceptProp 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.

Virtual structure

Sometimes it is impossible to define a static Go struct, for example when fields are only known at runtime. Yet, you may need to include such fields in JSON schema reflection pipeline.

For any reflected value, standalone or nested, you can define a virtual structure that would be treated as a native Go struct.

…

Custom Tags For Schema Definitions

If you're using additional libraries for validation, like for example go-playground/validator, you may want to infer validation rules into documented JSON schema.

go
type My struct {
    Foo *string `json:"foo" validate:"required"`
}

Normally, validate:"required" is not recognized, and you'd need to add required:"true" to have the rule exported to JSON schema.

However, it is possible to extend reflection with custom processing with InterceptProp option.

go
s, err := r.Reflect(My{}, jsonschema.InterceptProp(func(params jsonschema.InterceptPropParams) error {
    if !params.Processed {
        return nil
    }

    if v, ok := params.Field.Tag.Lookup("validate"); ok {
        if strings.Contains(v, "required") {
            params.ParentSchema.Required = append(params.ParentSchema.Required, params.Name)
        }
    }

    return nil
}))

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

Gocode-generationhacktoberfestjson-schema

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 18, 2026
Category编程语言
PricingOpen source

> Related tools

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言