I want to convert a struct to map in Golang. It would also be nice if I could use the JSON tags as keys in the created map (otherwise defaulting to field name).
Edit Dec 14, 2020
Since structs repo was archived, you can use mapstructure instead.
Edit TL;DR version, Jun 15, 2015
If you want the fast solution for converting a structure to map, see the accepted answer, upvote it and use that package.
Happy coding! :)
Original Post
So far I have this function, I am using the reflect package but I don't understand well how to use the package, please bear with me.
func ConvertToMap(model interface{}) bson.M {
ret := bson.M{}
modelReflect := reflect.ValueOf(model)
if modelReflect.Kind() == reflect.Ptr {
modelReflect = modelReflect.Elem()
}
modelRefType := modelReflect.Type()
fieldsCount := modelReflect.NumField()
var fieldData interface{}
for i := 0; i < fieldsCount; i++ {
field := modelReflect.Field(i)
switch field.Kind() {
case reflect.Struct:
fallthrough
case reflect.Ptr:
fieldData = ConvertToMap(field.Interface())
default:
fieldData = field.Interface()
}
ret[modelRefType.Field(i).Name] = fieldData
}
return ret
}
Also I looked at JSON package source code, because it should contain my needed implementation (or parts of it) but don't understand too much.
mgo/bson
package (which seems possible due to the use ofbson.M
), can't it already perform a conversion from a struct similar toencoding/json
?reflect
, and it is both slow and a royal pain to use; thejson
package is that way because using reflection is hard. My advice would be either to use something that already does the reflection parts for you (object-to-DB interfaces likegorp
ormgo
, builtin packages likejson
) or use (possibly repetitive) handwritten code to avoid reflection entirely. It's a situation where the approach that's natural and efficient in, say, JavaScript just isn't in Go.vice versa
. I looked at it ongodoc
but couldn't see how to convert from struct to map. Anyway, thanks.