Golang Array Of Struct To JSON

Kevin FOO
Dec 4, 2020

--

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.

< Back to all the stories I had written

--

--

Kevin FOO

A software engineer, a rock climbing, inline skating enthusiast, a husband, a father.