Implement json marshal / unmarshal so it can be used by PatchJson6902Transformer

This commit is contained in:
Phillip Wittrock
2020-04-01 14:33:18 -07:00
parent 21a544f188
commit 4a7b22cf23
2 changed files with 63 additions and 0 deletions

View File

@@ -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

View File

@@ -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()
}
}