Last active
October 17, 2017 11:42
-
-
Save MaksymTrykur/8a629911e376d84137446e148d239e6f to your computer and use it in GitHub Desktop.
json2yaml
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
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)) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
json2yaml
Usage
Specify a file:
Or pipe from stdin: