Skip to content

Commit 8a5b76c

Browse files
zombiezenrsc
authored andcommitted
json package: Fixed handling of nil values
Fixes #400. R=golang-dev, rsc https://golang.org/cl/167058
1 parent 7d7d95a commit 8a5b76c

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

src/pkg/json/struct.go

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -377,6 +377,11 @@ func writeStruct(w io.Writer, val *reflect.StructValue) os.Error {
377377
}
378378

379379
func writeValue(w io.Writer, val reflect.Value) (err os.Error) {
380+
if val == nil {
381+
fmt.Fprint(w, "null");
382+
return;
383+
}
384+
380385
switch v := val.(type) {
381386
case *reflect.StringValue:
382387
fmt.Fprintf(w, "%q", v.Get())
@@ -389,10 +394,15 @@ func writeValue(w io.Writer, val reflect.Value) (err os.Error) {
389394
case *reflect.StructValue:
390395
err = writeStruct(w, v)
391396
case *reflect.ChanValue,
392-
*reflect.InterfaceValue,
393397
*reflect.PtrValue,
394398
*reflect.UnsafePointerValue:
395399
err = &MarshalError{val.Type()}
400+
case *reflect.InterfaceValue:
401+
if v.IsNil() {
402+
fmt.Fprint(w, "null")
403+
} else {
404+
err = &MarshalError{val.Type()}
405+
}
396406
default:
397407
value := val.(reflect.Value);
398408
fmt.Fprint(w, value.Interface());

src/pkg/json/struct_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -177,6 +177,7 @@ type marshalTest struct {
177177

178178
var marshalTests = []marshalTest{
179179
// basic string
180+
marshalTest{nil, "null"},
180181
marshalTest{true, "true"},
181182
marshalTest{false, "false"},
182183
marshalTest{123, "123"},
@@ -185,11 +186,14 @@ var marshalTests = []marshalTest{
185186
marshalTest{"teststring", `"teststring"`},
186187
marshalTest{[4]int{1, 2, 3, 4}, "[1,2,3,4]"},
187188
marshalTest{[]int{1, 2, 3, 4}, "[1,2,3,4]"},
189+
marshalTest{[]interface{}{nil}, "[null]"},
188190
marshalTest{[][]int{[]int{1, 2}, []int{3, 4}}, "[[1,2],[3,4]]"},
189191
marshalTest{map[string]string{"one": "one"}, `{"one":"one"}`},
190192
marshalTest{map[string]int{"one": 1}, `{"one":1}`},
193+
marshalTest{map[string]interface{}{"null": nil}, `{"null":null}`},
191194
marshalTest{struct{}{}, "{}"},
192195
marshalTest{struct{ a int }{1}, `{"a":1}`},
196+
marshalTest{struct{ a interface{} }{nil}, `{"a":null}`},
193197
marshalTest{struct {
194198
a int;
195199
b string;

0 commit comments

Comments
 (0)