Last active
November 28, 2021 06:30
-
-
Save jd-boyd/119b290f881a0148b515 to your computer and use it in GitHub Desktop.
A Json pretty printer written in golang.
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 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 wrote:
MarshalIndent
callsIndent
to do the pretty-printing, so you can just doIndent
rather thanUnmarshal
followed byMarshalIndent
.
What would that code look like?
Wow, blast from the past. :)
https://golang.org/pkg/encoding/json/#Indent
https://golang.org/pkg/encoding/json/#example_Indent
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
MarshalIndent
callsIndent
to do the pretty-printing, so you can just doIndent
rather thanUnmarshal
followed byMarshalIndent
.