Why Golang cannot generate json from struct with front lowercase character?

Go uses case to determine whether a particular identifier is public or private within the context of your package. In your first example, the fields are not visible to json.Marshal because it is not part of the package containing your code. When you changed the fields to be upper case, they became public so could be exported.

If you need to use lower case identifiers in your JSON output though, you can tag the fields with the desired identifiers. For example:

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

Leave a Comment