I'm trying to omit nil interface values
package main
import (
"fmt"
"encoding/json"
)
type MyStruct struct{
Val interface{} `json:"val,omitempty"`
}
func main() {
var s []string
s = nil
m := MyStruct{
Val : s,
}
b, _:= json.Marshal(m)
fmt.Println(string(b))
}
Here is the playground link https://play.golang.org/p/cAE1IrSPgm This outputs
{"val":null}
Why is it not treating it as an empty value? Is there a way to omit these nil values from json.
From the documentation:
Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless
- the field's tag is "-", or
- the field is empty and its tag specifies the "omitempty" option.
The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero.
The reason it is not omitting is stated here
An interface value is nil only if the inner value and type are both unset, (nil, nil). In particular, a nil interface will always hold a nil type. If we store a nil pointer of type *int inside an interface value, the inner type will be *int regardless of the value of the pointer: (*int, nil). Such an interface value will therefore be non-nil even when the pointer inside is nil.
eg:
var s []string
s = nil
var temp interface{}
fmt.Println(temp==nil) // true
temp = s
fmt.Println(temp==nil) // false
For your case, you can do
https://play.golang.org/p/ZZ_Vzwq4QF
or
https://play.golang.org/p/S5lMgqVXuB