Home > Backend Development > Golang > Why Does My Go Struct Produce an Empty JSON Object When Marshalling?

Why Does My Go Struct Produce an Empty JSON Object When Marshalling?

Mary-Kate Olsen
Release: 2024-12-26 00:28:10
Original
1021 people have browsed it

Why Does My Go Struct Produce an Empty JSON Object When Marshalling?

JSON Marshalling in Go: Case Sensitivity of Struct Fields

When attempting to generate JSON from a struct in Go, one may encounter unexpected results if the fields of the struct begin with lowercase characters. Consider the following struct:

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

Marshalling this struct to JSON will result in an empty JSON object {}. This is because, by convention, Go uses the case of an identifier to determine its visibility within a package. By beginning the field names with lowercase characters, they are marked as private and inaccessible to the json.Marshal function.

To resolve this issue, one can either make the field names public by capitalizing the first letter of each word:

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

Or, if one wishes to use lowercase field names in the JSON output, they can use tags to specify the desired JSON names:

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

By using tags, one can customize the JSON field names while maintaining the privacy of the struct fields in Go.

The above is the detailed content of Why Does My Go Struct Produce an Empty JSON Object When Marshalling?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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