Skip to content

Instantly share code, notes, and snippets.

@flowerinthenight
Created September 5, 2017 14:33
Show Gist options
  • Save flowerinthenight/caa8ae4a0112f25eeabb67d0fbd837dd to your computer and use it in GitHub Desktop.
Save flowerinthenight/caa8ae4a0112f25eeabb67d0fbd837dd to your computer and use it in GitHub Desktop.
JSON prettifier function in Go
var Pad int = 2
func Indent(count int) string {
pad := ""
for i := 0; i < count; i++ {
pad += " "
}
return pad
}
// JSON returns a prettified JSON string of `v`.
func JSON(v interface{}, indent int) string {
var out bytes.Buffer
var b []byte
pad := Indent(indent)
_, ok := v.(string)
if !ok {
tmp, err := json.Marshal(v)
if err != nil {
return err.Error()
}
b = tmp
} else {
b = []byte(v.(string))
}
err := json.Indent(&out, b, "", pad)
if err != nil {
return err.Error()
}
return out.String()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment