Golang Struct Won't Marshal to JSON [duplicate

2019-07-20 08:00发布

问题:

This question already has an answer here:

  • My structures are not marshalling into json [duplicate] 3 answers

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.

回答1:

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"`
}
  • Working example: http://play.golang.org/p/Lg3cTO7DVk
  • Documentation: http://golang.org/pkg/encoding/json/#Marshal