I'm using reflect in golang to make a new initialized slice. But the moment I json.Marshal this new reflected slice, I get a JSON null value instead of a []. See this example here where I compare two cases:
package main
import (
"encoding/json"
"reflect"
"log"
)
func makeslice(slice interface{}) interface{} {
return reflect.New(reflect.TypeOf(slice)).Elem().Interface()
}
func main() {
s0 := []int{2,3,5}
s1 := makeslice(s0).([]int)
js1,e1 := json.Marshal(s1)
log.Println("case 1:",reflect.TypeOf(s1),reflect.ValueOf(s1),e1,string(js1))
s2 := []int{}
js2,e2 := json.Marshal(s2)
log.Println("case 2:",reflect.TypeOf(s2),reflect.ValueOf(s2),e2,string(js2))
}
This gives output of:
case 1: []int [] <nil> null
case 2: []int [] <nil> []
Notice that case 1 and case 2 produce exactly the same log output except for the final json string, where the first case shows null and the second case shows [].
Why is this the case? What I want is for case 1 to show [] instead because my friend's client side application is always expecting an array, and a zero length array should not be shown as a null.
What am I doing wrong?