Last active
January 2, 2016 20:29
-
-
Save larryli/8357193 to your computer and use it in GitHub Desktop.
json indent formatter
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
// 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