/gflatten

Golang for map and struct flatten library

Primary LanguageGoMIT LicenseMIT

cloudmate logo

gflatten

by Cloudmate


Cloudmate Golang


About

Golang for map and struct flatten library

Install

go get -u github.com/cloudmatelabs/gflatten

Usage

Insert Map

import "github.com/cloudmatelabs/gflatten"

src := map[string]any{
	"foo": []any{
		"bar", "baz",
	},
	"foobar": map[string]any{
		"foo": []any{
			"baz",
			map[string]any{
				"bar": map[string]any{
					"baz": "foobar",
				},
			},
		},
	},
}
option := gflatten.Option{
  ParameterDelimiter: ".",
  ArrayWrap:          gflatten.WRAP.SQUARE_BRACKET,
}
/* postgres style
option := gflatten.Option{
  ParameterDelimiter: "->",
  ArrayDelimiter:     "->",
  ParameterWrap:      gflatten.WRAP.SINGLE_QUOTE,
}
*/
/* mysql style
option := gflatten.Option{
  Prefix:             "$",
  ParameterDelimiter: ".",
  ArrayWrap:          gflatten.WRAP.SQUARE_BRACKET,
}
*/
dest, err := gflatten.Flatten(src, option)
/*
dest = map[string]any{
  "foo[0]":                "bar",
  "foo[1]":                "baz",
  "foobar.foo[0]":         "baz",
  "foobar.foo[1].bar.baz": "foobar",
}
*/

Insert Struct

import "github.com/cloudmatelabs/gflatten"

type bar struct {
	Baz string `json:"baz"`
}
type foobar struct {
	Foo []bar `json:"foo"`
}
type input struct {
	Foo    []string `json:"foo"`
	Foobar foobar   `json:"foobar"`
}

src := input{
	Foo: []string{"bar", "baz"},
	Foobar: foobar{
		Foo: []bar{
			{Baz: "baz"},
			{Baz: "foobar"},
		},
	},
}
option := gflatten.Option{
  ParameterDelimiter: ".",
  ArrayWrap:          gflatten.WRAP.SQUARE_BRACKET,
}
dest, err := gflatten.Flatten(src, option)
/*
dest = map[string]any{
  "foo[0]":            "bar",
	"foo[1]":            "baz",
	"foobar.foo[0].baz": "baz",
	"foobar.foo[1].baz": "foobar",
}
*/

Option

  • Prefix(optional)
  • ParameterDelimiter(optional)
  • ArrayDelimiter(optional)
  • ParameterWrap(optional) -> gflatten.WRAP
  • ArrayWrap(optional) -> gflatten.WRAP

gflatten.WRAP

  • SQUARE_BRACKET: []
  • SINGLE_QUOTE: ''
  • DOUBLE_QUOTE: ""
  • BACKTICK: ``
  • NONE