Skip to content

Commit

Permalink
encoding/json: skip unexpected null values
Browse files Browse the repository at this point in the history
As discussed in issue 2540, nulls are allowed for any type in JSON so they should not result in an error during Unmarshal.
Fixes #2540.

R=rsc
CC=golang-dev
https://golang.org/cl/6759043
  • Loading branch information
rickar authored and rsc committed Nov 12, 2012
1 parent 17623c0 commit c90739e
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 3 deletions.
4 changes: 1 addition & 3 deletions src/pkg/encoding/json/decode.go
Expand Up @@ -617,12 +617,10 @@ func (d *decodeState) literalStore(item []byte, v reflect.Value, fromQuoted bool
switch c := item[0]; c {
case 'n': // null
switch v.Kind() {
default:
d.saveError(&UnmarshalTypeError{"null", v.Type()})
case reflect.Interface, reflect.Ptr, reflect.Map, reflect.Slice:
v.Set(reflect.Zero(v.Type()))
// otherwise, ignore null for primitives/string
}

case 't', 'f': // true, false
value := c == 't'
switch v.Kind() {
Expand Down
47 changes: 47 additions & 0 deletions src/pkg/encoding/json/decode_test.go
Expand Up @@ -953,3 +953,50 @@ func TestInterfaceSet(t *testing.T) {
}
}
}

// JSON null values should be ignored for primitives and string values instead of resulting in an error.
// Issue 2540
func TestUnmarshalNulls(t *testing.T) {
jsonData := []byte(`{
"Bool" : null,
"Int" : null,
"Int8" : null,
"Int16" : null,
"Int32" : null,
"Int64" : null,
"Uint" : null,
"Uint8" : null,
"Uint16" : null,
"Uint32" : null,
"Uint64" : null,
"Float32" : null,
"Float64" : null,
"String" : null}`)

nulls := All{
Bool: true,
Int: 2,
Int8: 3,
Int16: 4,
Int32: 5,
Int64: 6,
Uint: 7,
Uint8: 8,
Uint16: 9,
Uint32: 10,
Uint64: 11,
Float32: 12.1,
Float64: 13.1,
String: "14"}

err := Unmarshal(jsonData, &nulls)
if err != nil {
t.Errorf("Unmarshal of null values failed: %v", err)
}
if !nulls.Bool || nulls.Int != 2 || nulls.Int8 != 3 || nulls.Int16 != 4 || nulls.Int32 != 5 || nulls.Int64 != 6 ||
nulls.Uint != 7 || nulls.Uint8 != 8 || nulls.Uint16 != 9 || nulls.Uint32 != 10 || nulls.Uint64 != 11 ||
nulls.Float32 != 12.1 || nulls.Float64 != 13.1 || nulls.String != "14" {

t.Errorf("Unmarshal of null values affected primitives")
}
}

0 comments on commit c90739e

Please sign in to comment.