json - Golang 结构不会编码为 JSON

标签 json struct go marshalling

我正在尝试将 Go 中的结构编码为 JSON,但它不会编码,我不明白为什么。

我的结构定义

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"`
}

创建并编码(marshal)测试结构

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 数据,数据存储正确并且可以打印。它只是不会编码(marshal),这很奇怪,因为结构中包含的所有内容都可以自行编码(marshal)为 JSON。

最佳答案

这是一个常见错误:您没有导出 PodsCondensedPodCondensed 结构中的值,因此 json 包无法使用它。在变量名称中使用大写字母即可:

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

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

关于json - Golang 结构不会编码为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29856890/

相关文章:

c - 如何在结构数组中初始化数组?

c++ - 使用结构中的 ncurses 扩展字符

c++ - 使用 malloc 在 C++ 中动态分配结构

go - 为什么我看到应该是单行编写器的多行标准输出?

javascript - 用于构造查询的 JSON 数据的有效方法

c# - IErrorHandler 在 HTTP 状态代码为 401 Unauthorized 时返回错误的消息正文

android - 在Titanium中将大JSON存储在iOS和Android中

python - json 文件中的 "Expecting property name enclosed in double quotes"

go - 无法在elasticsearch中保存UUID

macos - OSX 10.10.2 - cmd 启动未定义显示