Golang json.Marshal() return null for empty slice

Iman Tung
May 16, 2021

--

Today I found out that json.Marshal() weirdly return null for an empty slice but make sense.

var slice []string
b, _ := json.Marshal(slice)
fmt.Println(string(b)) // Output: null

The workaround is to initiate empty slice using make() function.

var slice []string
slice = make([]string, 0)
b, _ := json.Marshal(slice)
fmt.Println(string(b)) // Output: []

I thought make() will make fixed length slice and append() will trigger an error, but it totally fine. That's why in go they called it to slice instead of an array, the behavior is slightly different with the fixed-length array in another language.

var slice []string
slice = make([]string, 0)
fmt.Println(len(slice)) // Output: 0

slice = append(slice, "some-string")
fmt.Println(len(slice)) // Output: 1

b, _ := json.Marshal(slice)
fmt.Println(string(b)) // Output: ["some-string"]

Thanks to Dan Ott’s article for the insight

Previously published in https://imantung.github.io at 18 Apr 2019

--

--

Iman Tung
Iman Tung

Written by Iman Tung

Technology to write, life to grateful. Overthinking is good, only if it has the output. Fundamental is the main concern.

No responses yet