First thing, is to build an array from this struct to be a part of the final JSON result:
type Part struct {
Id string
Username string
Score string
}
Populating the array and get total scores:
var partArr []Part
var allscores decimal.Decimal
for _, result := range users {
partArr = append(partArr, Part{
id: string(result.id),
username: fmt.Sprintf("%s", result.username),
quantity: fmt.Sprintf("%s", result.score),
})
allscores = allscores+result.score
}
And then add it to another struct (ToSend):
type ToSend struct {
Parts []Part
Scores decimal.Decimal
}
toSend := &ToSend{
Parts: partArr,
Scores: allscores,
}
We format it to JSON:
toJson, err := json.Marshal(ToSend)
if err != nil {
log.Fatal("Cannot encode to JSON ", err)
}
But the result is not the waited one:
{"Parts":[{},{},{},{},{}], "Scores":"1850"}
It seem that Parts
field is containing empty contents ! Which is not exact, since if I print it in a String, I get the real infos inside it (+ the scores are calculated correctly - This mean infos are there).
WHat I did wrong please ?