The codes below is an example of converting an array of structs into JSON.
package main
import (
"log"
"encoding/json"
)
type Fruit struct {
Name string `json:"name"`
Quantity int `json:"quantity"`
}
func main() {
a := Fruit{Name:"Apple",Quantity:1}
o := Fruit{Name:"Orange",Quantity:2}
var fs []Fruit
fs = append(fs, a)
fs = append(fs, o)
log.Println(fs)
j, _ := json.Marshal(fs)
log.Println(string(j))
j, _ = json.MarshalIndent(fs, "", " ")
log.Println(string(j))
}
Running it will generate output as below.
In order to convert to JSON, the back tick enclosed description for the struct field is very important. Without it, the JSON output will be empty.