nilslice

package module
v0.0.0-...-646f70f Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 5, 2024 License: MIT Imports: 1 Imported by: 0

README

nilslice.Initialize(obj) - fix null arrays in 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. https://github.com/golang/go/issues/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": []}

Install

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

Authors

License

MIT license

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Initialize

func Initialize(obj interface{}) interface{}

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL