Giter VIP home page Giter VIP logo

nilslice's Introduction

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. 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": []}

Install

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

Authors

License

MIT license

nilslice's People

Contributors

vojtechvitek avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar

nilslice's Issues

Support for map

Hi. Thanks for the handy library first.

Seems the implementation is not working for map at the mo. When I try:

var a []string
m := map[string][]string{
	"k": a,
}
b, _ = json.Marshal(Initialize(m))
fmt.Println(string(b))

I got:

{"k":null}

I have tried to add:

func initializeNils(v reflect.Value) {
	// Dereference pointer(s).
	for v.Kind() == reflect.Ptr && !v.IsNil() {
		v = v.Elem()
	}

	if v.Kind() == reflect.Slice {
		// Initialize a nil slice.
		if v.IsNil() && v.CanSet() {
			v.Set(reflect.MakeSlice(v.Type(), 0, 0))
			return
		}

		// Recursively iterate over slice items.
		for i := 0; i < v.Len(); i++ {
			item := v.Index(i)
			initializeNils(item)
		}
	}

	// Recursively iterate over struct fields.
	if v.Kind() == reflect.Struct {
		for i := 0; i < v.NumField(); i++ {
			field := v.Field(i)
			initializeNils(field)
		}
	}

+	if v.Kind() == reflect.Map {
+		for _, key := range v.MapKeys() {
+			value := v.MapIndex(key)
+			initializeNils(value)
+		}
+	}
}

But with no effect. I debugged to find out that seems in this case value.CanSet() is false because map value is not addressable (reference).

Would be appreciated if anyone can find a solution to this!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.