json2go: github.com/m-zajac/json2go Index | Examples | Files

package json2go

import "github.com/m-zajac/json2go"

Package json2go implements decoding json strings to go type representation.

Index

Examples

Package Files

ast.go ast_printer.go doc.go json_node.go names.go parser.go type.go

type JSONParser Uses

type JSONParser struct {
    ExtractCommonStructs bool
    // contains filtered or unexported fields
}

JSONParser parses successive json inputs and returns go representation as string

func NewJSONParser Uses

func NewJSONParser(rootTypeName string) *JSONParser

NewJSONParser creates new json Parser

Code:

inputs := []string{
    `{"line":{"start":{"x":12.1,"y":2.8},"end":{"x":12.1,"y":5.67}}}`,
    `{"triangle":[{"x":2.34,"y":2.1}, {"x":45.1,"y":6.7}, {"x":4,"y":94.6}]}`,
}

parser := NewJSONParser("Document")
parser.ExtractCommonStructs = true

for _, in := range inputs {
    parser.FeedBytes([]byte(in))
}

res := parser.String()
fmt.Println(res)

Output:

type Document struct {
	Line	*struct {
		End	XY	`json:"end"`
		Start	XY	`json:"start"`
	}	`json:"line,omitempty"`
	Triangle	[]XY	`json:"triangle,omitempty"`
}
type XY struct {
	X	float64	`json:"x"`
	Y	float64	`json:"y"`
}

func (*JSONParser) ASTDecls Uses

func (p *JSONParser) ASTDecls() []ast.Decl

ASTDecls returns ast type declarations

func (*JSONParser) FeedBytes Uses

func (p *JSONParser) FeedBytes(input []byte) error

FeedBytes consumes json input as bytes. If input is invalid, json unmarshalling error is returned

func (*JSONParser) FeedValue Uses

func (p *JSONParser) FeedValue(input interface{})

FeedValue consumes one of:

* simple type (int, float, string, etc.)
* []interface{} - each value must meet these requirements
* map[string]interface{}  - each value must meet these requirements

json.Unmarshal to empty interface value provides perfect input (see example)

Code:

var v interface{}
json.Unmarshal([]byte(`{"line":{"start":{"x":12.1,"y":2.8},"end":{"x":12.1,"y":5.67}}}`), &v)

parser := NewJSONParser("Document")
parser.FeedValue(v)
res := parser.String()
fmt.Println(res)

Output:

type Document struct {
	Line struct {
		End	struct {
			X	float64	`json:"x"`
			Y	float64	`json:"y"`
		}	`json:"end"`
		Start	struct {
			X	float64	`json:"x"`
			Y	float64	`json:"y"`
		}	`json:"start"`
	} `json:"line"`
}

func (*JSONParser) String Uses

func (p *JSONParser) String() string

String returns string representation of go struct fitting parsed json values

Package json2go imports 11 packages (graph). Updated 2017-10-06. Refresh now. Tools for package owners.