Skip to content

Instantly share code, notes, and snippets.

@miquella
Last active August 29, 2015 13:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miquella/9983898 to your computer and use it in GitHub Desktop.
Save miquella/9983898 to your computer and use it in GitHub Desktop.
JSON Formatter
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strings"
"text/template"
)
func main() {
data, err := ioutil.ReadAll(os.Stdin)
if err != nil {
fmt.Fprintf(os.Stderr, "reading stdin failed: %s", err)
os.Exit(1)
}
v := make(map[string]interface{})
err = json.Unmarshal(data, &v)
if err != nil {
fmt.Fprintf(os.Stderr, "invalid json: %s", err)
os.Exit(2)
}
if len(os.Args) < 2 {
out, err := json.MarshalIndent(v, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "failed to write json: %s", err)
os.Exit(3)
}
fmt.Fprint(os.Stdout, string(out))
} else {
delimiter := ""
for _, arg := range os.Args[1:] {
fmt.Fprint(os.Stdout, delimiter)
t := template.New("Arg")
if strings.Contains(arg, "{{") {
_, err = t.Parse(arg)
} else {
_, err = t.Parse(fmt.Sprintf("{{.%s}}", arg))
}
if err != nil {
fmt.Fprintf(os.Stderr, "cannot parse template field: %s", err)
continue
}
err = t.Execute(os.Stdout, v)
if err != nil {
fmt.Fprintf(os.Stderr, "failed to execute template: %s", err)
os.Exit(3)
}
delimiter = "\n"
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment