json2go

package module
v0.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 30, 2023 License: BSD-3-Clause, MIT Imports: 12 Imported by: 0

README

json2go

GoDocBuild Status

Generate Go structs from JSON with struct tags: can specify type name, package name, and additional field tag keys with the CLI app.

The type may be one of the following:

* struct
* map[string]T
* map[string][]T

By default, a struct will be generated.

If the source JSON is an array of objects, the first element in the array will be used to generate the definition(s). Any objects within the JSON will result in additional embedded struct types.

The generated Go code will be part of package main unless another package name is set. Optionally, the import statement for encoding/json can be added to the Go source code.

The source JSON can also be written to a provided writer.

Keys with underscores, _, are converted to MixedCase. If any part of a key with underscores matches the list of common initialisms, that element is uppercased, e.g "person_id" becomes "personID". Keys starting with characters that are invalid for Go variable names have those characters discarded, unless they are a number, 0-9, which are converted to their word equivalents. All fields are exported and the JSON field tag for the field is generated using the original JSON key value.

If a field's value is null, the field's type will be interface{}, as that field's type is not determinable.

There is also a json2go CLI app. See that README for more info and examples; including how to install it.

Examples:

map[string][]T

Source JSON:

{
  "Blackhawks": [
    {
      "name": "Tony Esposito",
      "number": 35,
      "position": "Goal Tender"
    },
    {
      "name": "Stan Mikita",
      "number": 21,
      "position": "Center"
    }
  ]
}

Using Team as the parent type name and Player as the struct name:

package main

type Team map[string][]Player

type Player struct {
	Name     string `json:"name"`
	Number   int    `json:"number"`
	Position string `json:"position"`
}

struct

Source JSON from http://json.org/example.html:

{
	"widget": {
		"debug": "on",
		"window": {
 			"title": "Sample Konfabulator Widget",
         		"name": "main_window",
         		"width": 500,
         		"height": 500
 		},
 		"image": {
         		"src": "Images/Sun.png",
         		"name": "sun1",
         		"hOffset": 250,
         		"vOffset": 250,
         		"alignment": "center"
 		},
 		"text": {
 			"data": "Click Here",
         		"size": 36,
         		"style": "bold",
         		"name": "text1",
         		"hOffset": 250,
         		"vOffset": 100,
         		"alignment": "center",
         		"onMouseUp": "sun1.opacity = (sun1.opacity / 100) * 90;"
 		}
	}
}

Using Thing as the parent type name results in:

package main

type Thing struct {
	 Widget `json:"widget"
}
type Widget struct {
	Debug  string `json:"debug"`
	Image  `json:"image"`
	Text   `json:"text"`
	Window `json:"window"`
}

type Image struct {
	Alignment string `json:"alignment"`
	HOffset   int    `json:"hOffset"`
	Name      string `json:"name"`
	Src       string `json:"src"`
	VOffset   int    `json:"vOffset"`
}

type Text struct {
	Alignment string `json:"alignment"`
	Data      string `json:"data"`
	HOffset   int    `json:"hOffset"`
	Name      string `json:"name"`
	OnMouseUp string `json:"onMouseUp"`
	Size      int    `json:"size"`
	Style     string `json:"style"`
	VOffset   int    `json:"vOffset"`
}

type Window struct {
	Height int    `json:"height"`
	Name   string `json:"name"`
	Title  string `json:"title"`
	Width  int    `json:"width"`
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GenMapType

func GenMapType(typeName, name string, tagKeys []string, data []byte) ([]byte, error)

GenMapType unmarshals JSON-encoded data that is in the form of map[string][]Type and returns both the type declaration and the struct definition(s) for Type.

Types

type ShortWriteError

type ShortWriteError struct {
	// contains filtered or unexported fields
}

func (ShortWriteError) Error

func (e ShortWriteError) Error() string

type Transmogrifier

type Transmogrifier struct {

	// ImportJSON is used to control whether or not an import statement
	// for encoding/json should be generated.
	ImportJSON bool
	// WriteJSON is used to control whether or not the source JSON
	// should be written.  The JSON will be written using MarshalIndent
	// with '\t', tab, as the indent.  This only applies when the output
	// destination is not stdout.
	WriteJSON bool
	// MapType is used for JSON data that is map[string]interface{},
	// map[string][]interface{}, or a slice of either of the two. If
	// true, instead of generating a struct definition for the type, the
	// type will be either map[string]T or map[string][]T.  When the
	// created type is a map, the name of the struct T should be set
	// using SetStructName.  If it isn't set, T will be named Struct.
	//
	// If false, a struct definition will be generated for the type.
	MapType bool
	// contains filtered or unexported fields
}

Transmogrifier turns JSON into Go struct definitions.

func NewTransmogrifier

func NewTransmogrifier(name string, r io.Reader, w io.Writer) *Transmogrifier

NewTransmogrifier returns a new transmogrifier that reads from r and writes to w. The name is the name of the type that will be defined from the JSON. Embedded struct names, if there are any embedded structs, are derived from their associated key value.

func (*Transmogrifier) Gen

func (t *Transmogrifier) Gen() error

Gen generates the struct definitions and outputs it to W.

func (*Transmogrifier) SetJSONWriter

func (t *Transmogrifier) SetJSONWriter(w io.Writer)

SetJSONWriter set's the writer to which the original json is written to, This is most useful when getting the JSON from stdin.

func (*Transmogrifier) SetPkg

func (t *Transmogrifier) SetPkg(s string)

SetPkg set's the package name to s. The package name will be lowercased.

func (*Transmogrifier) SetStructName

func (t *Transmogrifier) SetStructName(s string)

SetStructName sets the name of the type derived from the interface{} portion of JSON that is of type map[string]interface{}. This is used when MapType is set to true. If MapType is set to true but typeName is not set, Struct will be used as the type name.

func (*Transmogrifier) SetTagKeys

func (t *Transmogrifier) SetTagKeys(v []string) error

SetTagKeys set's the additional keys that should be added to struct tags. This list should not include `json` as the `json` tag key is always defined for each field.

Directories

Path Synopsis
cmd
json2go
json2go generates Go type definitions from JSON encoded objects as defined in RFC 4627.
json2go generates Go type definitions from JSON encoded objects as defined in RFC 4627.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL