Frage

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?

War es hilfreich?

Lösung

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/

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top