Skip to content

Commit

Permalink
encoding/json: don't match field name if a JSON struct tag is present.
Browse files Browse the repository at this point in the history
Fixes #3566.

R=rsc
CC=golang-dev
https://golang.org/cl/6139048
  • Loading branch information
dsymonds committed May 1, 2012
1 parent dae2992 commit c3c8e35
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 4 deletions.
13 changes: 9 additions & 4 deletions src/pkg/encoding/json/decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -504,10 +504,15 @@ func (d *decodeState) object(v reflect.Value) {
}
// First, tag match
tagName, _ := parseTag(tag)
if tagName == key {
f = sf
ok = true
break // no better match possible
if tagName != "" {
if tagName == key {
f = sf
ok = true
break // no better match possible
}
// There was a tag, but it didn't match.
// Ignore field names.
continue
}
// Second, exact field name match
if sf.Name == key {
Expand Down
8 changes: 8 additions & 0 deletions src/pkg/encoding/json/decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ type T struct {
Z int `json:"-"`
}

type U struct {
Alphabet string `json:"alpha"`
}

type tx struct {
x int
}
Expand Down Expand Up @@ -72,6 +76,10 @@ var unmarshalTests = []unmarshalTest{
// Z has a "-" tag.
{`{"Y": 1, "Z": 2}`, new(T), T{Y: 1}, nil},

{`{"alpha": "abc", "alphabet": "xyz"}`, new(U), U{Alphabet: "abc"}, nil},
{`{"alpha": "abc"}`, new(U), U{Alphabet: "abc"}, nil},
{`{"alphabet": "xyz"}`, new(U), U{}, nil},

// syntax errors
{`{"X": "foo", "Y"}`, nil, nil, &SyntaxError{"invalid character '}' after object key", 17}},
{`[1, 2, 3+]`, nil, nil, &SyntaxError{"invalid character '+' after array element", 9}},
Expand Down

0 comments on commit c3c8e35

Please sign in to comment.