سؤال

Trying to parse a map[int] to user defined struct in go:

Here are the data schemas.

type Recommendation struct {
    Book  int     `json:"book"`
    Score float64 `json:"score"`
}

Here is the json marshaling:

ureco := make(map[int]data.Recommendation)
ureco, _ = reco.UserRunner()

json, _ := json.Marshal(ureco)
fmt.Println(json)

Where reco.UserRunner() returns the appropriate struct type.

This prints an empty json object:

[]

UPDATE:

error message:

json: unsupported type: map[int]data.Recommendation

So how do I json a map of structs? or is there an alternative approach?

هل كانت مفيدة؟

المحلول

If you just need to marshal it, you could just iterate over your map and turn it into a slice.

slc := make([]data.Recommendation)
for _, val := range ureco {     
    slc = append(out, val)
}
json, _ := json.Marshal(slc)

You can see a simple example with a map[int]string here: http://play.golang.org/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top