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
+9.7k Golang : Fix - does not implement sort.Interface (missing Len method)
+4.6k Unix/Linux/MacOSx : Get local IP address
+12.9k Golang : Get uploaded file name or access uploaded files
+15.8k Golang : XML to JSON example
+35.6k Upload multiple files with Go
+6.5k SSL : How to check if current certificate is sha1 or sha2 from command line
+18.2k Golang : Convert seconds to human readable time format example
+11.7k Android Studio : Password input and reveal password example
+5.5k Android Studio : Hello World example
+9k Golang : Get escape characters \u form from unicode characters
+3.8k Python : Find out the variable type and determine the type with simple test
+10.5k CodeIgniter : Import Linkedin data