Marshalling empty slice to empty JSON array instead of null in Go

You’d better don’t make them angry and make them happy giving them the proper `[]` empty array value. How to do that? Easily.

When you are creating the new slice like var people []Person you created new slice with you get the nil pointer to people var. And then there is a comprehensively a null value in output JSON. But if you create new slice with people := make([]Person, 0) you get the desired output. Or you can use people := []Person{}for same result too. See the whole code below or try it in playground. Tell me if the Frontend colleague invited you for a beer then.

In JSON APIs you often need to return array of data. In your Go code you probably use the slice []NameOfTheType to keep the list of the items. But when it comes to marshalling to JSON when the slice is empty you may get the JSON output contains null instead of an empty array. You should (but most of the time should not) see the faces of frontend developers when they face null instead of expected [] and try to iterate over it in JS 🙂


Continue Reading
Close Menu