From 4a7b22cf234cb949ad7bb0f9eb3e02cccc9b5fff Mon Sep 17 00:00:00 2001 From: Phillip Wittrock Date: Wed, 1 Apr 2020 14:33:18 -0700 Subject: [PATCH] Implement json marshal / unmarshal so it can be used by PatchJson6902Transformer --- kyaml/yaml/types.go | 24 ++++++++++++++++++++++++ kyaml/yaml/types_test.go | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/kyaml/yaml/types.go b/kyaml/yaml/types.go index ed325fb2c..f09f7ade2 100644 --- a/kyaml/yaml/types.go +++ b/kyaml/yaml/types.go @@ -5,6 +5,7 @@ package yaml import ( "bytes" + "encoding/json" "fmt" "io/ioutil" "strings" @@ -681,6 +682,29 @@ func (rn *RNode) GetAssociativeKey() string { return "" } +func (rn *RNode) MarshalJSON() ([]byte, error) { + s, err := rn.String() + if err != nil { + return nil, err + } + + m := map[string]interface{}{} + if err := Unmarshal([]byte(s), &m); err != nil { + return nil, err + } + + return json.Marshal(m) +} + +func (rn *RNode) UnmarshalJSON(b []byte) error { + r, err := Parse(string(b)) + if err != nil { + return err + } + rn.value = r.value + return nil +} + // checkKey returns true if all elems have the key func checkKey(key string, elems []*Node) bool { count := 0 diff --git a/kyaml/yaml/types_test.go b/kyaml/yaml/types_test.go index 3812f4e37..7805295b0 100644 --- a/kyaml/yaml/types_test.go +++ b/kyaml/yaml/types_test.go @@ -4,6 +4,7 @@ package yaml import ( + "strings" "testing" "github.com/stretchr/testify/assert" @@ -47,3 +48,41 @@ spec: t.FailNow() } } + +func TestRNode_UnmarshalJSON(t *testing.T) { + instance := &RNode{} + err := instance.UnmarshalJSON([]byte(`{"hello":"world"}`)) + if !assert.NoError(t, err) { + t.FailNow() + } + actual, err := instance.String() + if !assert.NoError(t, err) { + t.FailNow() + } + + expected := `{"hello": "world"}` + if !assert.Equal(t, + strings.TrimSpace(expected), strings.TrimSpace(actual)) { + t.FailNow() + } +} + +func TestRNode_MarshalJSON(t *testing.T) { + instance, err := Parse(` +hello: world +`) + if !assert.NoError(t, err) { + t.FailNow() + } + + actual, err := instance.MarshalJSON() + if !assert.NoError(t, err) { + t.FailNow() + } + + expected := `{"hello":"world"}` + if !assert.Equal(t, + strings.TrimSpace(expected), strings.TrimSpace(string(actual))) { + t.FailNow() + } +}