- Notifications
You must be signed in to change notification settings - Fork8
Go struct utilities with reflection for JSON data decoding, map-liked data accessing, dynamic struct building and more
License
goldeneggg/structil
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
struct + util =structil, for runtime and dynamic environment in Go.
I'd like to ...
- conveniently handle and decode the known or unknown formatted JSON/YAML
- conveniently dive into the specific field in nested struct
- simply verify if a field with the specified name and type exists in object
- etc
with Go reflection package experimentally.
*** JSON and YAML format is known or unknown ***JSON →→→→→→→→→→→→→→→→↓ →→ (known format) struct →→→→→→→→→→→↓→→→ (use struct directly) ↓ ↑ ↓ ↓→→ map →→→ (unknown format) "DynamicStruct" →→→→→→ "Getter", "Finder" ↑YAML →→→→→→→→→→→→→→→→↑ ↑(and other formats) →↑
Please seemy medium post as well.
Try printing the struct definition fromthe unknown formatted JSON decoding.
package mainimport ("fmt""github.com/goldeneggg/structil/dynamicstruct/decoder")funcmain() {unknownJSON:= []byte(`{"string_field":"かきくけこ","int_field":45678,"bool_field":false,"object_field":{"id":12,"name":"the name","nested_object_field": {"address": "Tokyo","is_manager": true}},"array_string_field":["array_str_1","array_str_2"],"array_struct_field":[{"kkk":"kkk1","vvvv":"vvv1"},{"kkk":"kkk2","vvvv":"vvv2"}],"null_field":null}`)// create `Decoder` from JSONdec,err:=decoder.FromJSON(unknownJSON)iferr!=nil {panic(err) }// - If `nest` is true, nested object attributes will be also decoded to struct recursively// - If `nest` is false, nested object attributes will be decoded to `map[string]interface{}`nest:=true// - If `useTag` is true, JSON Struct tags are defineduseTag:=true// create `DynamicStruct` from `Decoder`ds,err:=dec.DynamicStruct(nest,useTag)iferr!=nil {panic(err) }// print struct definition from `DynamicStruct`fmt.Println(ds.Definition())}
This program will print a Go struct definition string as follows.
// - Type name is "DynamicStruct" (raname is available)// - Field names are automatically camelized from input json attribute names// - Fields are ordered by field nametypeDynamicStructstruct {ArrayStringField []string`json:"array_string_field"`ArrayStructField []struct {Kkkstring`json:"kkk"`Vvvvstring`json:"vvvv"` }`json:"array_struct_field"`BoolFieldbool`json:"bool_field"`IntFieldfloat64`json:"int_field"`NullFieldinterface {}`json:"null_field"`ObjectFieldstruct {Idfloat64`json:"id"`Namestring`json:"name"`NestedObjectFieldstruct {Addressstring`json:"address"`IsManagerbool`json:"is_manager"` }`json:"nested_object_field"` }`json:"object_field"`StringFieldstring`json:"string_field"`}
And seeexample code.
We can convert fromthe unknown formatted JSON toGetter
viaDynamicStruct
withdecoder.JSONToGetter
function.
Seeexample code.
We can access a struct using field name string, like (typed) map withstructil.NewGetter
function.
g,err:=structil.NewGetter(structOrStructPointerVariable)// get num of struct fieldsg.NumField()// names of struct fieldsg.Names()// return true if struct has a "fName" fieldg.Has(fName)// get "fName" field value of the original struct as stringg.String(fName)// return true if "fName" field value of the original struct is float64g.IsFloat64(fName)// convert from struct to map[string]interface{}g.ToMap()// get as `Getter` if "fName" field is a (nested) structgNest,ok:=g.GetGetter(fName)gNest.NumField()gNest.Names()
Seeexample code
Getter.MapGet
method provides theMap collection function for slice of struct
Seeexample code
We can convert fromthe unknown formatted JSON toDynamicStruct
withDecoder
(fromdecoder.FromJSON
function) andDecoder.DynamicStruct
method.
Seeexample code.
We can create the dynamic and runtime struct.
Seeexample code
We can access usefully nested struct fields using field name string.
Seeexample code
We can create a Finder from the configuration file that have some finding target keys. We support some file formats of configuration file such asyaml
,json
,toml
and more.
Seeexample code
Thanks for the awesome configuration management libraryspf13/viper.
Seethis file
It's the latest benchmark result that is executed on GitHub Actions runner instance.
About
Go struct utilities with reflection for JSON data decoding, map-liked data accessing, dynamic struct building and more