Skip to content

Commit 63485f5

Browse files
authored
Merge pull request #1318 from agis/types-json-null-handling
Fix types.JSON.MarshalJSON to handle nil values
2 parents 8385710 + bf3897e commit 63485f5

File tree

2 files changed

+17
-0
lines changed

2 files changed

+17
-0
lines changed

types/json.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,9 @@ func (j *JSON) UnmarshalJSON(data []byte) error {
4646

4747
// MarshalJSON returns j as the JSON encoding of j.
4848
func (j JSON) MarshalJSON() ([]byte, error) {
49+
if j == nil {
50+
return []byte("null"), nil
51+
}
4952
return j, nil
5053
}
5154

types/json_test.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,20 @@ func TestJSONUnmarshalJSON(t *testing.T) {
7676
}
7777
}
7878

79+
func TestJSONMarshalJSON_Null(t *testing.T) {
80+
t.Parallel()
81+
82+
var j JSON
83+
res, err := j.MarshalJSON()
84+
if err != nil {
85+
t.Error(err)
86+
}
87+
88+
if !bytes.Equal(res, []byte(`null`)) {
89+
t.Errorf("Expected %q, got %v", `null`, res)
90+
}
91+
}
92+
7993
func TestJSONMarshalJSON(t *testing.T) {
8094
t.Parallel()
8195

0 commit comments

Comments
 (0)