Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Encode nil slices as empty arrays #62

Open
lukechampine opened this issue Jul 11, 2020 · 2 comments
Open

Encode nil slices as empty arrays #62

lukechampine opened this issue Jul 11, 2020 · 2 comments
Labels
bug Something isn't working
Milestone

Comments

@lukechampine
Copy link

By default, the json package marshals zero-valued (nil) slices as null, whereas merely empty slices are marshalled as []:

var s []int
json.Marshal(s) // -> null
s = []int{}
json.Marshal(s) // -> []

If the JSON is later consumed by a Go client, this generally isn't an issue, since both null and [] will be decoded as a slice with no elements, and Go code typically doesn't distinguish between nil and empty slices. However, clients in other languages may choke on null, e.g.:

let arr = request(endpoint)
let len = arr.length // invalid if arr === null

To avoid this, zero-valued slices should be replaced with empty slices prior to encoding. There are a few ways to do this, but unfortunately none of them are trivial. Perhaps the best approach for Rosetta would be to use a JSON codegen tool such as easyjson, which supports a NilSliceAsEmpty option. This would also improve encoding/decoding performance.

@patrick-ogrady
Copy link
Contributor

patrick-ogrady commented Jul 12, 2020

Thanks for posting this issue @lukechampine. Definitely something we need to fix (marking this as a bug)!

@patrick-ogrady patrick-ogrady added the bug Something isn't working label Jul 12, 2020
@patrick-ogrady patrick-ogrady added this to the v0.4.0 milestone Jul 19, 2020
@Mama54y
Copy link

Mama54y commented Jun 6, 2022

Read more

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Development

No branches or pull requests

3 participants