Go structs code-gen from JSON Schemas
Needed it, made it, sharing it: go-fromjsonschema generates Go type definitions (ready to json.Unmarshal
into) from a JSON Schema definition (proper JSD only — not just some sample *.json
) file.
Caution: contains a few strategically placed panic
s for edge cases
not-yet-considered/implemented/handled/needed. If it panic
s for your JSON
Schema, report!
-
Use it like this main.go does..
-
..to turn a JSON Schema like this..
-
..into a monster
.go
package ofstruct
(et al) type-defs like this
Usage
var (
// Will be appended to the resulting generated package doc-comment summary
GoPkgDesc = "Package codegen'd via github.com/metaleap/go-fromjsonschema"
// Default JSON-to-Go type mappings, `number` could be tweaked to `float64` depending on the use-case at hand
TypeMapping = map[string]string
)
type JsonDef
type JsonDef struct
Represents a top-level type definition, or a property definition,
a type-reference, an embedded anonymous struct
/object
type definition, or an
array
/map
element type definition..
func (*JsonDef) EnsureProps
func (propNamesAndTypes map[string]string)
type JsonSchema
type JsonSchema struct
Top-level declarations of a JSON Schema
func NewJsonSchema
func NewJsonSchema(jsonSchemaDefSrc string) (*JsonSchema, error)
Obtains from the given JSON Schema source a *JsonSchema
that can be passed to
Generate
. err
is nil
unless unmarshaling the specified jsonSchemaDefSrc
failed.
func (*JsonSchema) ForceCopyProps
func (fromBaseTypeName string, toBaseTypeName string, pnames ...string)
func (*JsonSchema) Generate
func (goPkgName string, generateDecodeHelpersForBaseTypeNames map[string]string, generateHandlinScaffoldsForBaseTypes map[string]string, generateCtorsForBaseTypes ...string) string
Generate a Go package source with type-defs representing the Defs
in jsd
(typically obtained via NewJsonSchema
).
Arguments beyond goPkgName
generate further code beyond the type-defs: these
may all be nil
/zeroed, or if one "sounds like what you need", check the source
for how they're handled otherwise =)