Last active
December 12, 2017 00:37
-
-
Save penguinpowernz/8347549e5682c2e675633a54da7be88f to your computer and use it in GitHub Desktop.
Pretty print JSON files faster than json_pp
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
// 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