One of the most frustrating things with Go is how it handles empty arrays when encoding JSON. Rather than returning what is traditionally expected, an empty array, it instead returns null. For example, the following:

package main

import (
	"encoding/json"
	"fmt"
)

// Bag holds items
type Bag struct {
	Items []string
}

// PrintJSON converts payload to JSON and prints it
func PrintJSON(payload interface{}) {
	response, _ := json.Marshal(payload)
	fmt.Printf("%s\n", response)
}


func main() {
	bag1 := Bag{}
	PrintJSON(bag1)
}

Outputs:

{"Items":null}

This occurs because of how the json package handles nil slices:

Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.

There are some proposals to amend the json package to handle nil slices:

But, as of this writing, these proposals have not been accepted. As such, in order to overcome the problem of null arrays, we have to set nil slices to empty slices.

#tips-and-tricks #go #json #golang

Handling Null JSON Arrays in Golang (Go)
64.15 GEEK