It easy to get an empty list when working with string by using []string{}
:
import (
"encoding/json"
"fmt"
)
func main() {
slice1 := []string{} // non-nil but zero-length
json1, _ := json.Marshal(slice1)
fmt.Printf("%s\n", json1) // []
}
The output of code above is []
, BUT when I work with []byte
even using []byte{}
returns ""
. How should I get an empty list like what I get in []string{}
?
import (
"encoding/json"
"fmt"
)
func main() {
slice2 := []byte{} // non-nil but zero-length
json2, _ := json.Marshal(slice2)
fmt.Printf("%s\n", json2) // ""
}
CodePudding user response:
See the docs:
Array and slice values encode as JSON arrays, except that []byte encodes as a base64-encoded string, and a nil slice encodes as the null JSON value.
The part in bold is why you get ""
. If you want []
from []byte{}
, you need a custom named []byte
type that implements the json.Marshaler
interface.
Or, if you're looking for a "slice of integers", then use []N
where N
can be any of the basic integer types just not the uint8
type. The uint8
type will not work because byte
is an alias of uint8
so []uint8
is identical to []byte
and json.Marshal
will output ""
for that as well.