/jsonschema-go

JSON Schema mapping for Go

Primary LanguageGoMIT LicenseMIT

JSON Schema structures for Go

Build Status Coverage Status GoDevDoc time tracker Code lines Comments

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

Reflector

Documentation.

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"
// }

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.

Implementing interfaces on a type

There are a few interfaces that can be implemented on a type to customize JSON Schema generation.

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

Configuring the reflector

Additional centralized configuration is available with jsonschema.ReflectContext and Reflect options.