英文:
Why Golang cannot generate json from struct with front lowercase character?
问题
我正在尝试从我创建的结构体中打印JSON结果:
type Machine struct {
m_ip string
m_type string
m_serial string
}
m := &Machine{m_ip: "test", m_type: "test", m_serial: "test"}
m_json, _ := json.Marshal(m)
fmt.Println(m_json)
然而,返回的结果只是 {}
。
其次,我尝试将单词的首字母改为大写,如下所示:
type Machine struct{
MachIp string
MachType string
MachSerial string
}
这样就可以正常工作了!为什么以小写字母开头的单词不起作用呢?
英文:
I am trying to print json result from struct I created as following:
type Machine struct {
m_ip string
m_type string
m_serial string
}
and print out
m:= &Machine{ m_ip:"test", m_type:"test", m_serial:"test" }
m_json:= json.Marshal(m)
fmt.Println(m_json)
However, result returned just {}
Secondly,I tried to changed the first letter of words to Uppercase as follow:
type Machine struct{
MachIp string
MachType string
MachSerial string
}
and it works! Why doesn't the word with lowercase character at the front work, anyway?
答案1
得分: 81
Go语言使用大小写来确定特定标识符在包的上下文中是公开的还是私有的。在你的第一个例子中,这些字段对于json.Marshal
来说是不可见的,因为它不是包含你代码的包的一部分。当你将这些字段改为大写时,它们变成了公开的,因此可以被导出。
然而,如果你需要在JSON输出中使用小写标识符,你可以使用所需的标识符对字段进行标记。例如:
type Machine struct{
MachIp string `json:"m_ip"`
MachType string `json:"m_type"`
MachSerial string `json:"m_serial"`
}
英文:
Go uses case to determine whether a particular identifier is public or private within the context of your package. In your first example, the fields are not visible to json.Marshal
because it is not part of the package containing your code. When you changed the fields to be upper case, they became public so could be exported.
If you need to use lower case identifiers in your JSON output though, you can tag the fields with the desired identifiers. For example:
type Machine struct{
MachIp string `json:"m_ip"`
MachType string `json:"m_type"`
MachSerial string `json:"m_serial"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论