From d353c6ee77cc3b834a36087832c7c3ca828aabb9 Mon Sep 17 00:00:00 2001 From: Masaaki Goshima Date: Mon, 26 Oct 2020 19:00:29 +0900 Subject: [PATCH] Add YAMLToJSON and JSONToYAML --- yaml.go | 26 ++++++++++++++++++++++++++ yaml_test.go | 38 ++++++++++++++++++++++++++++++++++++++ 2 files changed, 64 insertions(+) diff --git a/yaml.go b/yaml.go index b4e76b48..8f56c713 100644 --- a/yaml.go +++ b/yaml.go @@ -183,3 +183,29 @@ func FormatError(e error, colored, inclSource bool) string { return e.Error() } + +// YAMLToJSON convert YAML bytes to JSON. +func YAMLToJSON(bytes []byte) ([]byte, error) { + var v interface{} + if err := UnmarshalWithOptions(bytes, &v, UseOrderedMap()); err != nil { + return nil, errors.Wrapf(err, "failed to unmarshal") + } + out, err := MarshalWithOptions(v, JSON()) + if err != nil { + return nil, errors.Wrapf(err, "failed to marshal with json option") + } + return out, nil +} + +// JSONToYAML convert JSON bytes to YAML. +func JSONToYAML(bytes []byte) ([]byte, error) { + var v interface{} + if err := UnmarshalWithOptions(bytes, &v, UseOrderedMap()); err != nil { + return nil, errors.Wrapf(err, "failed to unmarshal from json bytes") + } + out, err := Marshal(v) + if err != nil { + return nil, errors.Wrapf(err, "failed to marshal") + } + return out, nil +} diff --git a/yaml_test.go b/yaml_test.go index b2c34d67..8141dd22 100644 --- a/yaml_test.go +++ b/yaml_test.go @@ -344,3 +344,41 @@ b: *b` t.Fatalf("failed to marshal: expected:[%q] but got [%q]", expected, actual) } } + +func Test_YAMLToJSON(t *testing.T) { + yml := ` +foo: + bar: + - a + - b + - c +a: 1 +` + actual, err := yaml.YAMLToJSON([]byte(yml)) + if err != nil { + t.Fatal(err) + } + expected := `{"foo": {"bar": ["a", "b", "c"]}, "a": 1}` + if expected+"\n" != string(actual) { + t.Fatalf("failed to convert yaml to json: expected [%q] but got [%q]", expected, actual) + } +} + +func Test_JSONToYAML(t *testing.T) { + json := `{"foo": {"bar": ["a", "b", "c"]}, "a": 1}` + expected := ` +foo: + bar: + - a + - b + - c +a: 1 +` + actual, err := yaml.JSONToYAML([]byte(json)) + if err != nil { + t.Fatal(err) + } + if expected != "\n"+string(actual) { + t.Fatalf("failed to convert json to yaml: expected [%q] but got [%q]", expected, actual) + } +}