goext/reflectext/convertToMap.go
Mike Schwörer 14f39a9162
Some checks failed
Build Docker and Deploy / Run goext test-suite (push) Failing after 1m43s
v0.0.416
2024-03-18 11:19:01 +01:00

88 lines
1.3 KiB
Go

package reflectext
import (
"encoding/json"
"reflect"
)
type ConvertStructToMapOpt struct {
KeepJsonMarshalTypes bool
}
func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) any {
opt := ConvertStructToMapOpt{}
if len(opts) > 0 {
opt = opts[0]
}
return reflectToMap(reflect.ValueOf(v), opt)
}
func reflectToMap(fv reflect.Value, opt ConvertStructToMapOpt) any {
if fv.Kind() == reflect.Ptr {
if fv.IsNil() {
return nil
} else {
return reflectToMap(fv.Elem(), opt)
}
}
if fv.Kind() == reflect.Func {
// skip
return nil
}
if fv.Kind() == reflect.Array {
arrlen := fv.Len()
arr := make([]any, arrlen)
for i := 0; i < arrlen; i++ {
arr[i] = reflectToMap(fv.Index(i), opt)
}
return arr
}
if fv.Kind() == reflect.Slice {
arrlen := fv.Len()
arr := make([]any, arrlen)
for i := 0; i < arrlen; i++ {
arr[i] = reflectToMap(fv.Index(i), opt)
}
return arr
}
if fv.Kind() == reflect.Chan {
// skip
return nil
}
if fv.Kind() == reflect.Struct {
if opt.KeepJsonMarshalTypes && fv.Type().Implements(reflect.TypeFor[json.Marshaler]()) {
return fv.Interface()
}
res := make(map[string]any)
for i := 0; i < fv.NumField(); i++ {
if fv.Type().Field(i).IsExported() {
res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i), opt)
}
}
return res
}
return fv.Interface()
}