Home > Backend Development > Golang > Why Doesn't Go's `json.Marshal` Include Struct Fields with Lowercase Names?

Why Doesn't Go's `json.Marshal` Include Struct Fields with Lowercase Names?

Linda Hamilton
Release: 2024-12-25 01:21:11
Original
304 people have browsed it

Why Doesn't Go's `json.Marshal` Include Struct Fields with Lowercase Names?

Why Does Golang Fail to Generate JSON from a Struct with Lowercase Initial Character?

When attempting to marshal a struct into JSON, developers may encounter an unexpected issue where the result returns as an empty object. This behavior stems from Go's use of case to differentiate between private and public identifiers.

In the example provided, the struct Machine has fields with lowercase initial characters:

type Machine struct {
  m_ip string
  m_type string
  m_serial string
}
Copy after login

By default, Go considers identifiers with lowercase initial characters as private. This means that the fields in Machine are not visible to json.Marshal because it is not part of the same package as the code.

To resolve this issue, developers can opt to change the field names to uppercase, making them public:

type Machine struct {
  MachIp string
  MachType string
  MachSerial string
}
Copy after login

However, if developers wish to maintain lowercase identifiers in the JSON output, they can utilize JSON tags:

type Machine struct {
    MachIp     string `json:"m_ip"`
    MachType   string `json:"m_type"`
    MachSerial string `json:"m_serial"`
}
Copy after login

By adding json:"m_ip" to the MachIp field, for example, the resulting JSON will include the desired lowercase identifier. This is achieved because the JSON tag overrides the default case behavior.

The above is the detailed content of Why Doesn't Go's `json.Marshal` Include Struct Fields with Lowercase Names?. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template