Skip to content

Commit

Permalink
Add YAMLToJSON and JSONToYAML
Browse files Browse the repository at this point in the history
  • Loading branch information
goccy committed Oct 26, 2020
1 parent 81f720d commit d353c6e
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 0 deletions.
26 changes: 26 additions & 0 deletions yaml.go
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
38 changes: 38 additions & 0 deletions yaml_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
}
}

0 comments on commit d353c6e

Please sign in to comment.