0

I'm a new user converting an application to Go. I have something like the following which is working:

type Network struct {
        Ssid     string
        Security string
        Bitrate  string
}

func Scan(w http.ResponseWriter, r *http.Request) {
        output := runcmd(scripts+"scan.sh", true)
        bytes := []byte(output)
        var networks []Network
        json.Unmarshal(bytes, &networks)
        w.Header().Set("Content-Type", "application/json")
        json.NewEncoder(w).Encode(networks)
}

The problem is the old version didn't use capitals on the json variables returned.

I want the front-end to see ssid not Ssid. If I make the attributes in the struct lowercase the code no longer works as they become unexported variables.

Philip Kirkbride
  • 21,381
  • 38
  • 125
  • 225

2 Answers2

4

When the field names in your struct do not match the json field names, you can use field tags. eg:

Ssid string `json:"myOtherFieldName"`

Please read the json docs for more details.

Marc
  • 19,394
  • 6
  • 47
  • 51
1

This tool very convenient for learning:

https://mholt.github.io/json-to-go/

Give it example of JSON that you want it will recommend golang.

e.g. JSON

{
   "ssid": "some very long ssid",
   "security": "big secret",
   "bitrate": 1024
}

will suggest golang:

type AutoGenerated struct {
    Ssid     string `json:"ssid"`
    Security string `json:"security"`
    Bitrate  int    `json:"bitrate"`
}

now you can change AutogGenerated, Ssid, Security, Bitrate to whatever you want.

k1m190r
  • 1,213
  • 15
  • 26