Skip to content

Instantly share code, notes, and snippets.

@MaksymTrykur
Last active October 17, 2017 11:42
Show Gist options
  • Save MaksymTrykur/8a629911e376d84137446e148d239e6f to your computer and use it in GitHub Desktop.
Save MaksymTrykur/8a629911e376d84137446e148d239e6f to your computer and use it in GitHub Desktop.
json2yaml
package main
import (
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"os"
"gopkg.in/yaml.v2"
)
func check(err error) {
if err != nil {
fmt.Println(err)
os.Exit(1)
}
}
func source() (io.Reader, error) {
if len(os.Args) > 1 {
f, err := os.Open(os.Args[1])
if err != nil {
return nil, err
}
return f, nil
}
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
return os.Stdin, nil
}
return nil, errors.New("no input source")
}
func main() {
src, err := source()
check(err)
in, err := ioutil.ReadAll(src)
check(err)
if rc, ok := src.(io.ReadCloser); ok {
rc.Close()
}
var data interface{}
json.Unmarshal(in, &data)
check(err)
out, err := yaml.Marshal(data)
check(err)
fmt.Print(string(out))
}
@MaksymTrykur
Copy link
Author

json2yaml

Usage

Specify a file:

json2yaml ./example.json > ./example.yml

Or pipe from stdin:

cat ./example.yml | json2yaml > ./example.yml

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment