Golang : Clean formatting/indenting or pretty print JSON result
Problem:
Your Golang program is producing JSON result in a single line that looks like this :
["apple","orange","durian","pear"]
but you want to make the result human readable/clean formatted/indented or pretty print. How to do that?
Solution:
Instead of using json.Marshal()
function, use json.MarshalIndent()
function instead.
Example:
package main
import (
"encoding/json"
"fmt"
"strings"
)
func main() {
str := "apple orange durian pear"
// turn to slice
strSlice := strings.Fields(str)
fmt.Println("Slice : ", strSlice)
jsonPrettyPrint, _ := json.MarshalIndent(strSlice, "", " ")
fmt.Println("nicely indented/formatted JSON : \n", string(jsonPrettyPrint))
jsonWithOutIndent, _ := json.Marshal(strSlice)
fmt.Println("non-indented JSON : \n", string(jsonWithOutIndent))
}
output:
Slice : [apple orange durian pear]
nicely indented/formatted JSON :
[
"apple",
"orange",
"durian",
"pear"
]
non-indented JSON :
["apple","orange","durian","pear"]
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+18.2k Golang : Check if a directory exist or not
+10.1k Golang : Channels and buffered channels examples
+13.8k Golang : Tutorial on loading GOB and PEM files
+17.2k Golang : Get input from keyboard
+7.1k Golang : Fibonacci number generator examples
+27.8k Golang : dial tcp: too many colons in address
+14.9k Golang : Send email with attachment(RFC2822) using Gmail API example
+32.7k Golang : Copy directory - including sub-directories and files
+11.4k Golang : Intercept and process UNIX signals example
+5.3k Golang : Calculate half life decay example
+41.4k Golang : How to count duplicate items in slice/array?
+10.6k Generate Random number with math/rand in Go