Skip to content

Instantly share code, notes, and snippets.

@larryli
Last active January 2, 2016 20:29
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 larryli/8357193 to your computer and use it in GitHub Desktop.
Save larryli/8357193 to your computer and use it in GitHub Desktop.
json indent formatter
// echo {"a":"b"} | go run json-fmt.go [-prefix ""] [-indent " "]
// go run json-fmt.go [-prefix ""] [-indent " "] {\"a\":\"b\"}
// go run json-fmt.go [-prefix ""] [-indent " "] -file data.json
package main
import (
"encoding/json"
"flag"
. "gist.github.com/9521299.git"
"io/ioutil"
"os"
"strings"
)
func main() {
var (
prefix = flag.String("prefix", "", "prefix string")
indent = flag.String("indent", " ", "indent string")
file = flag.String("file", "", "fmt filename")
bufRead []byte
errRead error
data interface{}
)
flag.Parse()
if *file != "" {
bufRead, errRead = ioutil.ReadFile(*file)
} else if flag.NArg() > 0 {
bufRead = []byte(strings.Join(flag.Args(), " "))
} else {
bufRead, errRead = ioutil.ReadAll(os.Stdin)
}
Die(errRead, "Read Input")
err := json.Unmarshal(bufRead, &data)
Die(err, "Json Unmarshal")
bufWrite, errMarshal := json.MarshalIndent(data, *prefix, *indent)
Die(errMarshal, "Json Indent Marshal")
if *file != "" {
err := ioutil.WriteFile(*file, bufWrite, os.ModePerm)
Die(err, "Write Output")
} else {
_, err := os.Stdout.Write(bufWrite)
Die(err, "Write Output")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment