Golang结构不会统一到JSON [英] Golang Struct Won't Marshal to JSON
问题描述
我试图编组去一个结构转到JSON,但它不会编组,我不明白为什么。
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))
输出
[{tier2 [blue green]}]
{}
我不确定问题在这里,我为所有结构导出json数据,数据正在被正确存储并可用于打印。它只是不会做元帅,这很奇怪,因为结构中包含的所有东西都可以封装到JSON中。
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.
推荐答案
这是一个常见错误:您没有在 PodsCondensed
和 PodCondensed
结构中导出值,所以json软件包无法使用它。在变量名中使用大写字母这样做:
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"`
}
- 工作示例: http://play.golang.org/p/Lg3cTO7DVk
- 文档:< a href =http://golang.org/pkg/encoding/json/#Marshal =nofollow> http://golang.org/pkg/encoding/json/#Marshal
- Working example: http://play.golang.org/p/Lg3cTO7DVk
- Documentation: http://golang.org/pkg/encoding/json/#Marshal
这篇关于Golang结构不会统一到JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!