英文:
In Go, why is my JSON decoding not working here?
问题
我无法使标准库的encoding/json
包能够解码JSON对象。以下是一个最简示例:
b := []byte(`{"groups":[{"name":"foo"},{"name":"bar"}]}`)
type Group struct{ name string }
var contents struct {
groups []Group
}
err := json.Unmarshal(b, &contents)
fmt.Printf("contents = %+v\nerr = %+v\n", contents, err)
这段代码输出:
contents = {groups:[]}
err = nil
但我期望的输出是:
contents = {groups:[{name:foo} {name:bar}]}
我做错了什么?
英文:
I cannot get the standard library's encoding/json
package to work for decoding JSON objects. Here's a minimal example:
b := []byte(`{"groups":[{"name":"foo"},{"name":"bar"}]}`)
type Group struct{ name string }
var contents struct {
groups []Group
}
err := json.Unmarshal(b, &contents)
fmt.Printf("contents = %+v\nerr = %+v\n", contents, err)
This prints:
contents = {groups:[]}
err = nil
But I expect:
contents = {groups:[{name:foo} {name:bar}]}
What am I doing wrong?
答案1
得分: 14
字段名必须以大写字母开头:
type Group struct{ Name string }
var contents struct {
Groups []Group
}
英文:
The field names have to start with a capital letter:
type Group struct{ Name string }
var contents struct {
Groups []Group
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论