Golang Array Of Struct To JSON

The codes below is an example of converting an array of structs into JSON.

package main

import (

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)

j, _ := json.Marshal(fs)

j, _ = json.MarshalIndent(fs, "", " ")

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

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store