mesh-sdk-go icon indicating copy to clipboard operation
mesh-sdk-go copied to clipboard

Encode nil slices as empty arrays

Open lukechampine opened this issue 4 years ago • 2 comments

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.

lukechampine avatar Jul 11 '20 19:07 lukechampine

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

patrick-ogrady avatar Jul 12 '20 23:07 patrick-ogrady

Read more

Mama54y avatar Jun 06 '22 09:06 Mama54y