我正在尝试从我创建的结构中打印 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
}
它有效!为什么前面带小写字符的单词不管用?
最佳答案
Go 用例来确定特定标识符在包的上下文中是公共(public)的还是私有(private)的。在您的第一个示例中,这些字段对 json.Marshal
不可见,因为它不是包含您的代码的包的一部分。当您将字段更改为大写时,它们会变为公开的,因此可以导出。
如果您需要在 JSON 输出中使用小写标识符,您可以使用所需的标识符标记字段。例如:
type Machine struct{
MachIp string `json:"m_ip"`
MachType string `json:"m_type"`
MachSerial string `json:"m_serial"`
}
关于go - 为什么 Golang 不能从带有前小写字符的结构生成 json?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21825322/