Skip to content

Instantly share code, notes, and snippets.

@johnlonganecker
Last active October 25, 2021 11:28
Show Gist options
  • Save johnlonganecker/0b1f857781a902a558f34f1b467d5df8 to your computer and use it in GitHub Desktop.
Save johnlonganecker/0b1f857781a902a558f34f1b467d5df8 to your computer and use it in GitHub Desktop.
Convert Struct to Map Example
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
}
@johnlonganecker
Copy link
Author

Thanks for sharing rajan! I haven't even looked at this for awhile. I will make the change.

@xmlking
Copy link

xmlking commented Feb 7, 2021

any example for reverse?
ConvertMapToStruct(mp map[string]interface{}, &Address{})

@DasJott
Copy link

DasJott commented May 12, 2021

How about recursively convert if a field contains another struct?

@tareqmamari
Copy link

@xmlking try github.com/mitchellh/mapstructure

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment