2

I'm trying to marshal a struct in Go to JSON but it won't marshal and I can't understand why.

My struct definitions

type PodsCondensed struct {
    pods    []PodCondensed  `json:"pods"`
}

func (p *PodsCondensed) AddPod(pod PodCondensed) {
    p.pods = append(p.pods, pod)
}

type PodCondensed struct {
    name    string      `json:"name"`
    colors  []string    `json:"colors"`
}

Creating and marshaling a test struct

fake_pods := PodsCondensed{}

fake_pod := PodCondensed {
    name: "tier2",
    colors: []string{"blue", "green"},
}

fake_pods.AddPod(fake_pod)
fmt.Println(fake_pods.pods)

jPods, _ := json.Marshal(fake_pods)
fmt.Println(string(jPods))

Output

[{tier2 [blue green]}]
{}

I'm not sure what the issue is here, I export json data for all my structs, the data is being stored correctly and is available to print. It just wont marshal which is odd because everything contained in the struct can be marshaled to JSON on its own.

Colin Murphy
  • 1,105
  • 3
  • 12
  • 22

1 Answers1

3

This is a common mistake: you did not export values in the PodsCondensed and PodCondensed structures, so the json package was not able to use it. Use a capital letter in the variable name to do so:

type PodsCondensed struct {
    Pods    []PodCondensed  `json:"pods"`
}

type PodCondensed struct {
    Name    string      `json:"name"`
    Colors  []string    `json:"colors"`
}
julienc
  • 19,087
  • 17
  • 82
  • 82