Created
September 5, 2017 14:33
-
-
Save flowerinthenight/caa8ae4a0112f25eeabb67d0fbd837dd to your computer and use it in GitHub Desktop.
JSON prettifier function in Go
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
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