goext/reflectext/convertToMap.go
Mike Schwörer 7e16e799e4
All checks were successful
Build Docker and Deploy / Run goext test-suite (push) Successful in 1m28s
v0.0.381
2024-01-23 17:51:52 +01:00

73 lines
1013 B
Go

package reflectext
import "reflect"
func ConvertStructToMap(v any) any {
return reflectToMap(reflect.ValueOf(v))
}
func reflectToMap(fv reflect.Value) any {
if fv.Kind() == reflect.Ptr {
if fv.IsNil() {
return nil
} else {
return reflectToMap(fv.Elem())
}
}
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))
}
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))
}
return arr
}
if fv.Kind() == reflect.Chan {
// skip
return nil
}
if fv.Kind() == reflect.Struct {
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))
}
}
return res
}
return fv.Interface()
}