Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up

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

License

NotificationsYou must be signed in to change notification settings

golang-cz/nilslice

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

3 Commits
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Golang'sjson.Marshal() function has a very unfortunate behavior when encodingnil slices. It renders anull 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 allnil slices in a given object using areflect package.

typePayloadstruct {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

About

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

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp