Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

encoding: empty values are not considered during unmarshal #14708

Closed
azr opened this issue Mar 8, 2016 · 3 comments
Closed

encoding: empty values are not considered during unmarshal #14708

azr opened this issue Mar 8, 2016 · 3 comments

Comments

@azr
Copy link
Contributor

azr commented Mar 8, 2016

Hello there !

On any golang version (1.5 or 1.6 ).

# 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 !

@azr azr changed the title encoding: zero values are not considered during unmarshal encoding: empty values are not considered during unmarshal Mar 8, 2016
@ALTree
Copy link
Member

ALTree commented Mar 8, 2016

Dup of #14640 I believe.

@azr
Copy link
Contributor Author

azr commented Mar 8, 2016

oops sorry about that !

@ianlancetaylor
Copy link
Contributor

Closing as duplicate.

@golang golang locked and limited conversation to collaborators Mar 13, 2017
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

4 participants