mesh-sdk-go
mesh-sdk-go copied to clipboard
Encode nil slices as empty arrays
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.
Thanks for posting this issue @lukechampine. Definitely something we need to fix (marking this as a bug)!
Read more