Home > Enterprise >  Why is my json.Marshal() returning nothing? [duplicate]
Why is my json.Marshal() returning nothing? [duplicate]

Time:10-06

I'm trying to create a slice of JSON objects that has the following structure:

[
    {"id":"some identifier"},
    {"id":"some other identifier"}
]

My code is producing [{},{}]. Why is this happening?

Here is the code:

    type Topic struct {
        id string
    }

    topics := []Topic{
        {id: "some identifier"},
        {id: "some other identifier"},
    }

    fmt.Println(topics) // prints the topics as is, before marshaling

    tops, err := json.Marshal(topics)
    if err != nil {
        fmt.Println("got an error", err)
    }

    fmt.Println(string(tops)) // does not print the topics

CodePudding user response:

Because json sees only public fields - e.g. started with upper case.

Do like this:

type Topic struct {
    ID string `json:"id"`
}

topics := []Topic{
    {ID: "some identifier"},
    {ID: "some other identifier"},
}
  • Related