forked from ghodss/yaml
-
Notifications
You must be signed in to change notification settings - Fork 73
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
split yaml.go in marshal.go & unmarshal.go, rename functions and vari…
…ables, improve error messages & wrapping Signed-off-by: Inteon <42113979+inteon@users.noreply.github.com>
- Loading branch information
Showing
2 changed files
with
107 additions
and
94 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,43 @@ | ||
package yaml | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
|
||
"gopkg.in/yaml.v2" | ||
) | ||
|
||
// JSONToYAML Converts JSON to YAML. | ||
func JSONToYAML(j []byte) ([]byte, error) { | ||
// Convert the JSON to an object. | ||
var jsonObj interface{} | ||
|
||
// We are using yaml.Unmarshal here (instead of json.Unmarshal) because the | ||
// Go JSON library doesn't try to pick the right number type (int, float, | ||
// etc.) when unmarshalling to interface{}, it just picks float64 | ||
// universally. go-yaml does go through the effort of picking the right | ||
// number type, so we can preserve number type throughout this process. | ||
err := yaml.Unmarshal(j, &jsonObj) | ||
if err != nil { | ||
return nil, fmt.Errorf("error converting JSON to YAML: %w", err) | ||
} | ||
|
||
// Marshal this object into YAML. | ||
yamlBytes, err := yaml.Marshal(jsonObj) | ||
if err != nil { | ||
return nil, fmt.Errorf("error converting JSON to YAML: %w", err) | ||
} | ||
|
||
return yamlBytes, nil | ||
} | ||
|
||
// Marshal marshals the object into JSON then converts JSON to YAML and returns the | ||
// YAML. | ||
func Marshal(obj interface{}) ([]byte, error) { | ||
jsonBytes, err := json.Marshal(obj) | ||
if err != nil { | ||
return nil, fmt.Errorf("error marshaling into JSON: %w", err) | ||
} | ||
|
||
return JSONToYAML(jsonBytes) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters