Highly configurable struct to map converter. Converts map[string]any
into other maps as well.
- configuration outside the struct
- could be in a different package
- no need to modify original structs (by adding tags, implementing methods etc.)
- behaviour as a code - you provide code which will be run during conversion
- ability to:
- rename keys during conversion
- omit keys based on field name, value or tag etc.
- map elements during conversion
- specify which structs should be converted to maps
# Add mapify to your Go module:
go get github.com/elgopher/mapify
package main
import (
"fmt"
"github.com/elgopher/mapify"
)
// This example shows how to convert struct into map
func main() {
s := SomeStruct{Field: "value"}
// create Mapper instance. Here default parameters are used.
mapper := mapify.Mapper{}
// MapAny maps any object - this can be a struct, slice or map. The whole object is traversed in order to find
// all nested structs. Each struct will be converted to map[string]interface{}
result, err := mapper.MapAny(s)
if err != nil {
panic(err)
}
fmt.Printf("%+v", result) // map[Field:value]
}
type SomeStruct struct {
Field string
}
- Take an object which is a struct, map or slice.
- Traverse entire object looking for nested structs or maps.
- Filter elements (struct fields and map keys).
- Rename field names or map keys.
- Map (struct field or map values).