-2

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 ?

  • 9
    The declaration of struct Part looks ok, but when you're initializing the Parts array, the struct you're using have lower case member names, meaning they are not exported, and won't be included in the json. The code you included in your post is not the code you're running. Include your real code here. – Burak Serdar Oct 10 '19 at 23:45
  • Also, what is your go version? The json library on different version of go acts a little bit differently. – Koala Yeung Oct 11 '19 at 02:11
  • @Peter, not sure this is a duplicate. The question you referenced was due to unexported values. While the symptoms are the same, the causes here are different. – PassKit Oct 11 '19 at 06:54
  • The code given cannot compile (the struct definition and struct literal do not match). Please provide a [Minimal, Reproducible Example](https://stackoverflow.com/help/minimal-reproducible-example). – Adrian Oct 11 '19 at 13:45

1 Answers1

0

Your code as written is marshaling an empty struct:

toJson, err := json.Marshal(ToSend)

you should be marshling your object:

toJson, err := json.Marshal(toSend) // not json.Marshal(ToSend)
if err != nil {
    log.Fatal("Cannot encode to JSON ", err)
}

This doesn't explain why the scores are populated, but it's difficult to speculate without knowing what the decimal library is doing.

PassKit
  • 12,231
  • 5
  • 57
  • 75