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