You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
# http://play.golang.org/p/71ZtR0mX9K
package main
import (
"encoding/json"
"fmt"
)
type FooBar struct {
Foo int `json:"Foo,omitempty"`
Bar int `json:"Bar,omitempty"`
}
var (
foo1 = `{"Foo": 1}`
bar1 = `{"Bar": 1}`
)
func main() {
fb := FooBar{}
json.Unmarshal([]byte(foo1), &fb)
fmt.Printf("%+v\n", fb)
json.Unmarshal([]byte(bar1), &fb)
fmt.Printf("%+v\n", fb)
}
outputs
{Foo:1 Bar:0}
{Foo:1 Bar:0}
I assume it's because as its not set it's considered empty and omitted.
But this can provoque weird behaviours when you reuse structs twice or have an unmarshal loop that read a file. Or worse, when you rewrite a that file with a loop in a different format.
Possible solutions:
add a reset() builtin, the one that's called just after allocation ? How would that work with pointers ?
make the encoding pkgs reset unset fields in Unmarshal using reflection ?
just tell people to be careful
cheers !
The text was updated successfully, but these errors were encountered:
azr
changed the title
encoding: zero values are not considered during unmarshal
encoding: empty values are not considered during unmarshal
Mar 8, 2016
Hello there !
On any golang version (1.5 or 1.6 ).
outputs
I assume it's because as its not set it's considered empty and omitted.
But this can provoque weird behaviours when you reuse structs twice or have an unmarshal loop that read a file. Or worse, when you rewrite a that file with a loop in a different format.
Possible solutions:
reset()
builtin, the one that's called just after allocation ? How would that work with pointers ?cheers !
The text was updated successfully, but these errors were encountered: