Skip to content

Instantly share code, notes, and snippets.

@mgoldey
Created July 20, 2020 19:57
Show Gist options
  • Save mgoldey/8600b6878f05e13a463078a263fa4452 to your computer and use it in GitHub Desktop.
Save mgoldey/8600b6878f05e13a463078a263fa4452 to your computer and use it in GitHub Desktop.
demo that converts golang data structure to json schema
package main
import (
"encoding/json"
"fmt"
"github.com/alecthomas/jsonschema"
"time"
)
type TestUser struct {
ID int `json:"id"`
Name string `json:"name" jsonschema:"title=the name,description=The name of a friend,example=joe,example=lucy,default=alex"`
Friends []int `json:"friends,omitempty" jsonschema_description:"The list of IDs, omitted when empty"`
Tags map[string]interface{} `json:"tags,omitempty" jsonschema_extras:"a=b,foo=bar,foo=bar1"`
BirthDate time.Time `json:"birth_date,omitempty" jsonschema:"oneof_required=date"`
YearOfBirth string `json:"year_of_birth,omitempty" jsonschema:"oneof_required=year"`
Metadata interface{} `json:"metadata,omitempty" jsonschema:"oneof_type=string;array"`
FavColor string `json:"fav_color,omitempty" jsonschema:"enum=red,enum=green,enum=blue"`
}
func main() {
a := jsonschema.Reflect(&TestUser{})
actualJSON, _ := json.MarshalIndent(a, "", " ")
fmt.Printf(string(actualJSON))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment