Created
June 4, 2020 07:32
-
-
Save jvahldick/c7407b1528066d68a267b1ba02b1113c to your computer and use it in GitHub Desktop.
[Go] Converts structs into map[string]interface{}
This file contains hidden or 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
package structs | |
import ( | |
"encoding/json" | |
"reflect" | |
) | |
func ConvertToMapViaReflection(s interface{}) map[string]interface{} { | |
var m map[string]interface{} | |
el := reflect.ValueOf(&s).Elem() | |
elType := el.Type() | |
for i := 0; i < elType.NumField(); i++ { | |
m[elType.Field(i).Name] = el.Field(i).Interface() | |
} | |
return m | |
} | |
func ConvertToMapViaMarshalling(s interface{}) (map[string]interface{}, error) { | |
dataBytes, err := json.Marshal(s) | |
if err != nil { | |
return nil, err | |
} | |
var m map[string]interface{} | |
err = json.Unmarshal(dataBytes, &m) | |
if err != nil { | |
return nil, err | |
} | |
return m, nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment