Skip to content

Latest commit

 

History

4 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 
 
 
 
 

Repository files navigation

nilslice.Initialize(obj) - fix null arrays rendered by encoding/json

Golang's json.Marshal() function has a very unfortunate behavior when encoding nil slices. It renders a null value in JSON instead of an empty array [].

This issue has a couple of open issues (ie. golang/go#27589) but none of the proposed solutions were accepted into the standard library as of Aug 2023.

This lightweight Go package will help you mitigate the issue by recursively initializing all nil slices in a given object using a reflect package.

type Payload struct {
	Items []Item `json:"items"`
}

payload := &Payload{}

b, _ := json.Marshal(payload)
fmt.Println(string(b))
// {"items": null}

b, _ = json.Marshal(nilslice.Initialize(payload))
fmt.Println(string(b))
// {"items": []}

Fixed in encoding/json/v2 or bytedance/sonic

The original issue golang/go#27589 has been addressed in both encoding/json/v2 and github.com/bytedance/sonic packages.

Install

$ go get github.com/golang-cz/nilslice
import "github.com/golang-cz/nilslice"

Authors

License

MIT license

About

Golang: Recursively initialize all nil slices in a given object, so they json.Marshal() as empty array [] instead of null.

Topics

Resources

Stars

16 stars

Watchers

2 watching

Forks

Releases

Packages

Used by

Contributors

Languages