Last active
October 25, 2021 11:28
-
-
Save johnlonganecker/0b1f857781a902a558f34f1b467d5df8 to your computer and use it in GitHub Desktop.
Convert Struct to Map Example
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func ConvertStructToMap(st interface{}) map[string]interface{} { | |
reqRules := make(map[string]interface{}) | |
v := reflect.ValueOf(st) | |
t := reflect.TypeOf(st) | |
for i := 0; i < v.NumField(); i++ { | |
key := strings.ToLower(t.Field(i).Name) | |
typ := v.FieldByName(t.Field(i).Name).Kind().String() | |
structTag := t.Field(i).Tag.Get("json") | |
jsonName := strings.TrimSpace(strings.Split(structTag, ",")[0]) | |
value := v.FieldByName(t.Field(i).Name) | |
// if jsonName is not empty use it for the key | |
if jsonName != "" && jsonName != "-" { | |
key = jsonName | |
} | |
if typ == "string" { | |
if !(value.String() == "" && strings.Contains(structTag, "omitempty")) { | |
fmt.Println(key, value) | |
fmt.Println(key, value.String()) | |
reqRules[key] = value.String() | |
} | |
} else if typ == "int" { | |
reqRules[key] = value.Int() | |
} else { | |
reqRules[key] = value.Interface() | |
} | |
} | |
return reqRules | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
How about recursively convert if a field contains another struct?