struct <-> map[string]interface{} conversion

15717 views
Skip to first unread message

m

unread,
Aug 16, 2010, 9:47:05 PM8/16/10
to golang-nuts
Does there happen to be a quick conversion between the two? It would
be extremely convenient. Since interfaces only support methods.

Ostsol

unread,
Aug 16, 2010, 9:52:27 PM8/16/10
to golang-nuts
Type assertions are as fast as it gets.

-Daniel

Scott Lawrence

unread,
Aug 16, 2010, 9:54:25 PM8/16/10
to m, golang-nuts
Nothing particularly quick.

If you care to use the reflect package, you could do something like
(disclaimer: totally untested):

myMap := make(map[string]interface{})
myObj := // whatever
type := reflect.TypeOf(myobj).(*StructType) // myObj had better be a struct!
for i := 0; i < type.NumField(); i++ {
myMap[type.Field(i).Name] = // something
}

For the //something, I /think/ you have to do something with
Field.offset, which would require the unsafe package as well.


On 8/16/10, m <phill...@gmail.com> wrote:
> Does there happen to be a quick conversion between the two? It would
> be extremely convenient. Since interfaces only support methods.


--
Scott Lawrence

Steven

unread,
Aug 16, 2010, 11:06:19 PM8/16/10
to Scott Lawrence, m, golang-nuts
Beat me to the post, but here's a working example: http://ideone.com/XWtlo. It transfers what it can from one to the other. Figuring out how to use tags if they are available is left as an exercise to the reader (you can access a field tag using typ.Field(i).Tag, where typ is a *reflect.StructType)

Depending on your use case, you may want to just use a *reflect.StructValue instead of a map[string]interface{}, since it keeps track of the original struct (so you don't have to guess) and works automatically. Instead of mapVal["FieldName"], just use structVal.FieldByName("FieldName"). Its probably less efficient if you're going to be doing a lot of accesses, but its more straightforward.

RoboTamer

unread,
Dec 3, 2013, 3:18:02 PM12/3/13
to golan...@googlegroups.com

I am not sure what you need it for but this might help

package main
import(
    "fmt"
    "encoding/json"
)
 
type Envelop map[string]interface{}
type message struct {
    Type, Text string
}
 
func main(){
    var m = make(Envelop)
    m["message"] = message{"error","You can't do that!"}
    j, err := json.Marshal(&m)
    if err != nil {
        fmt.Println(err)
    }
    fmt.Printf("Struct: %s\n", m)
    fmt.Printf("JsonIn: %s\n", j)
    var mm map[string]Envelop
    err = json.Unmarshal(j, &mm)
    if err != nil {
        fmt.Println(err)
    }
    var ss Envelop
    ss = mm["message"]
    fmt.Println("MR: ", ss)
}
Reply all
Reply to author
Forward
0 new messages