Get "null" from json.NewEncoder(bodyBuf).Encode(body) of nil

For below code fragment

bodyBuf := &bytes.Buffer{}
var body interface{}
json.NewEncoder(bodyBuf).Encode(body)
fmt.Printf("%v", bodyBuf)

the output is “null” which is weird, since it is json encode, I prefer empty string or error

Here the reason which i get it by debug. The var, body, which type is interface, is not string type. So when u use it without initing it, it is null.
U can turn body to string type or add a " if " sentence if u prefer empty string or error.

thanks @lizhiyuzhong, but my understanding is, it should not return a string “null” since it is in json package, I think adding logic here https://github.com/golang/go/blob/master/src/encoding/json/stream.go#L202 makes more sense.
“”, “{}” or error is better than “null”

The encoding/json documentation says this:

Interface values encode as the value contained in the interface. A nil interface value encodes as the null JSON value.

The value of body is nil and so it seems reasonable to encode it as a JSON null.

Yes, i agree your understanding. When Encoding the “body”, the logic in line 219 will write “null” in a []byte. Changing here makes more sense as u say.

Thanks Sean, I did not notice the doc you mentioned, and seems it is the standard in Go that all nil value including slice will be marshaled to null, really good to know

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.