Skip to content

Commit

Permalink
Merge pull request #1318 from agis/types-json-null-handling
Browse files Browse the repository at this point in the history
Fix types.JSON.MarshalJSON to handle nil values
  • Loading branch information
stephenafamo authored Oct 18, 2023
2 parents 8385710 + bf3897e commit 63485f5
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
3 changes: 3 additions & 0 deletions types/json.go
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,9 @@ func (j *JSON) UnmarshalJSON(data []byte) error {

// MarshalJSON returns j as the JSON encoding of j.
func (j JSON) MarshalJSON() ([]byte, error) {
if j == nil {
return []byte("null"), nil
}
return j, nil
}

Expand Down
14 changes: 14 additions & 0 deletions types/json_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,20 @@ func TestJSONUnmarshalJSON(t *testing.T) {
}
}

func TestJSONMarshalJSON_Null(t *testing.T) {
t.Parallel()

var j JSON
res, err := j.MarshalJSON()
if err != nil {
t.Error(err)
}

if !bytes.Equal(res, []byte(`null`)) {
t.Errorf("Expected %q, got %v", `null`, res)
}
}

func TestJSONMarshalJSON(t *testing.T) {
t.Parallel()

Expand Down

0 comments on commit 63485f5

Please sign in to comment.