Skip to content

Instantly share code, notes, and snippets.

@jd-boyd
Last active November 28, 2021 06:30
Show Gist options
  • Star 10 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save jd-boyd/119b290f881a0148b515 to your computer and use it in GitHub Desktop.
Save jd-boyd/119b290f881a0148b515 to your computer and use it in GitHub Desktop.
A Json pretty printer written in golang.
//Build with: go build ./jsonpp.go
package main
import "encoding/json"
import "fmt"
import "io/ioutil"
import "os"
func main() {
if len(os.Args) != 2 {
fmt.Println("One argument, the json file to pretty-print is required")
os.Exit(-1)
}
fileName := os.Args[1]
byt, err := ioutil.ReadFile(fileName)
if err != nil {
panic(err)
}
var dat map[string] interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
b, err := json.MarshalIndent(dat, "", " ")
if err != nil {
panic(err)
}
b2 := append(b, '\n')
os.Stdout.Write(b2)
}
@gregmarr
Copy link

MarshalIndent calls Indent to do the pretty-printing, so you can just do Indent rather than Unmarshal followed by MarshalIndent.

@jhannah-mm
Copy link

jhannah-mm commented Mar 8, 2021

@gregmarr wrote:

MarshalIndent calls Indent to do the pretty-printing, so you can just do Indent rather than Unmarshal followed by MarshalIndent.

What would that code look like?

@gregmarr
Copy link

gregmarr commented Mar 8, 2021

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment