Skip to content

Instantly share code, notes, and snippets.

@penguinpowernz
Last active December 12, 2017 00:37
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 penguinpowernz/8347549e5682c2e675633a54da7be88f to your computer and use it in GitHub Desktop.
Save penguinpowernz/8347549e5682c2e675633a54da7be88f to your computer and use it in GitHub Desktop.
Pretty print JSON files faster than json_pp
// build by running go build ./jsonpp.go
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"os"
)
func usage() {
fmt.Println("Usage: jsonpp file.json")
fmt.Println(" cat file.json | jsonpp")
fmt.Println(" jsonpp < file.json")
fmt.Println("\nPretty print JSON files faster than json_pp")
}
func main() {
var data []byte
var err error
stat, _ := os.Stdin.Stat()
if (stat.Mode() & os.ModeCharDevice) == 0 {
buf := bytes.NewBuffer([]byte{})
io.Copy(buf, os.Stdin)
data = buf.Bytes()
} else {
if len(os.Args) != 2 {
usage()
os.Exit(1)
}
data, err = ioutil.ReadFile(os.Args[1])
if err != nil {
panic(err)
}
}
prettyPrint(data)
}
func prettyPrint(b []byte) {
var buf bytes.Buffer
if err := json.Indent(&buf, b, "", " "); err != nil {
panic(err)
}
io.Copy(os.Stdout, bytes.NewReader(buf.Bytes()))
fmt.Println()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment