From 70af06c62bcca85616178a7fa80e014878df0bbc Mon Sep 17 00:00:00 2001 From: Christian Wywiorski Date: Wed, 8 Apr 2015 19:02:24 -0400 Subject: [PATCH] implement json.Marshaler for data.Undefined and data.Null --- data/value.go | 5 +++++ data/value_test.go | 30 ++++++++++++++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/data/value.go b/data/value.go index 03e59c8..cdf37b6 100644 --- a/data/value.go +++ b/data/value.go @@ -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 } diff --git a/data/value_test.go b/data/value_test.go index f45b170..a77860f 100644 --- a/data/value_test.go +++ b/data/value_test.go @@ -1,6 +1,7 @@ package data import ( + "encoding/json" "reflect" "testing" ) @@ -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{} @@ -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) + } + } + } +}