Home >Backend Development >Golang >Why Does JSON Encoding Fail with Go Structs Having Lowercase Field Names?

Why Does JSON Encoding Fail with Go Structs Having Lowercase Field Names?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-26 11:27:18578browse

Why Does JSON Encoding Fail with Go Structs Having Lowercase Field Names?

Why Does JSON Encoding Fail for Structs with Lowercase Field Names in Go?

In Go, a struct's fields are only visible to the package in which it is defined if their first letter is uppercase. Attempting to encode a struct with lowercase field names, as shown below, will result in an empty JSON output:

type Machine struct {
  m_ip string
  m_type string
  m_serial string
}

func main() {
  m := &Machine{m_ip: "test", m_type: "test", m_serial: "test"}
  m_json, err := json.Marshal(m)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(m_json)) // Prints "{}"
}

This occurs because the fields are not visible to the json.Marshal function due to their lowercase first letters. However, changing the field names to uppercase, as follows, allows the JSON encoding to succeed:

type Machine struct {
  MachIp string
  MachType string
  MachSerial string
}

func main() {
  m := &Machine{MachIp: "test", MachType: "test", MachSerial: "test"}
  m_json, err := json.Marshal(m)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(m_json)) // Prints "{\"MachIp\":\"test\",\"MachType\":\"test\",\"MachSerial\":\"test\"}"
}

To encode a struct with lowercase field names, you can tag the fields with the desired JSON keys. For instance:

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

func main() {
  m := &Machine{MachIp: "test", MachType: "test", MachSerial: "test"}
  m_json, err := json.Marshal(m)
  if err != nil {
    fmt.Println(err)
    return
  }
  fmt.Println(string(m_json)) // Prints "{\"m_ip\":\"test\",\"m_type\":\"test\",\"m_serial\":\"test\"}"
}

By tagging the fields with the desired JSON keys, the struct can be encoded with lowercase field names, making it more convenient for certain scenarios.

The above is the detailed content of Why Does JSON Encoding Fail with Go Structs Having Lowercase Field Names?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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