From a8c6e39ac5f746450d675d9c430cc6fbe6b1b164 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Mike=20Schw=C3=B6rer?= Date: Tue, 10 Dec 2024 13:24:06 +0100 Subject: [PATCH] v0.0.549 --- goextVersion.go | 4 ++-- reflectext/convertToMap.go | 18 +++++++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/goextVersion.go b/goextVersion.go index bfb6a3e..35b36ee 100644 --- a/goextVersion.go +++ b/goextVersion.go @@ -1,5 +1,5 @@ package goext -const GoextVersion = "0.0.548" +const GoextVersion = "0.0.549" -const GoextVersionTimestamp = "2024-12-09T17:39:35+0100" +const GoextVersionTimestamp = "2024-12-10T13:24:06+0100" diff --git a/reflectext/convertToMap.go b/reflectext/convertToMap.go index 8b43a0c..289c773 100644 --- a/reflectext/convertToMap.go +++ b/reflectext/convertToMap.go @@ -4,11 +4,13 @@ import ( "encoding/json" "gogs.mikescher.com/BlackForestBytes/goext/langext" "reflect" + "strings" ) type ConvertStructToMapOpt struct { KeepJsonMarshalTypes bool MaxDepth *int + UseTagsAsKeys *string } func ConvertStructToMap(v any, opts ...ConvertStructToMapOpt) map[string]any { @@ -90,7 +92,21 @@ func reflectToMap(fv reflect.Value, depth int, opt ConvertStructToMapOpt) any { for i := 0; i < fv.NumField(); i++ { if fv.Type().Field(i).IsExported() { - res[fv.Type().Field(i).Name] = reflectToMap(fv.Field(i), depth+1, opt) + + k := fv.Type().Field(i).Name + if opt.UseTagsAsKeys != nil { + if tagval, ok := fv.Type().Field(i).Tag.Lookup(*opt.UseTagsAsKeys); ok { + if strings.Contains(tagval, ",") { + k = strings.TrimSpace(strings.Split(tagval, ",")[0]) + } else { + k = strings.TrimSpace(tagval) + } + } else { + continue + } + } + + res[k] = reflectToMap(fv.Field(i), depth+1, opt) } }