Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

implement json.Marshaler for data.Undefined and data.Null #24

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions data/value.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ func (v Map) Key(k string) Value {
return result
}

// Marshal ---------

func (v Undefined) MarshalJSON() ([]byte, error) { return []byte("null"), nil }
func (v Null) MarshalJSON() ([]byte, error) { return []byte("null"), nil }

// Truthy ----------

func (v Undefined) Truthy() bool { return false }
Expand Down
30 changes: 30 additions & 0 deletions data/value_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package data

import (
"encoding/json"
"reflect"
"testing"
)
Expand All @@ -17,6 +18,13 @@ var (
_ Value = Map{}
)

// Ensure custom marshalers are implemented

var (
_ json.Marshaler = Undefined{}
_ json.Marshaler = Null{}
)

func TestKey(t *testing.T) {
tests := []struct {
input interface{}
Expand Down Expand Up @@ -52,3 +60,25 @@ func TestIndex(t *testing.T) {
}
}
}

func TestCustomMarhshaling(t *testing.T) {
tests := []struct {
input interface{}
expected interface{}
}{
{Null{}, []byte("null")},
{Undefined{}, []byte("null")},
}

for _, test := range tests {
actual, err := json.Marshal(test.input)
if err != nil {
t.Errorf("unexpected error: %#v", err.Error())
}

if !reflect.DeepEqual(test.expected, actual) {
t.Errorf("%v => %#v, expected %#v", test.input, actual, test.expected)
}
}
}
}