Created
December 15, 2015 05:42
-
-
Save TripleDogDare/f7c86c95bc8c45a73f4e to your computer and use it in GitHub Desktop.
Go pretty print JSON
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
package main | |
import ( | |
"bytes" | |
"encoding/json" | |
"io" | |
"io/ioutil" | |
"os" | |
) | |
func main() { | |
var stream io.Reader | |
if len(os.Args) > 1 { | |
file, err := os.Open(os.Args[1]) | |
if err != nil { | |
os.Stderr.Write([]byte(err.Error())) | |
os.Exit(1) | |
} | |
defer file.Close() | |
stream = file | |
} else { | |
stream = os.Stdin | |
} | |
var out bytes.Buffer | |
buffer, err := ioutil.ReadAll(stream) | |
if err != nil { | |
os.Stderr.Write([]byte(err.Error())) | |
os.Exit(1) | |
} | |
json.Indent(&out, buffer, "", "\t") | |
out.WriteTo(os.Stdout) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment