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
+10.7k Golang : Reverse IP address for reverse DNS lookup example
+12.2k Golang : Parsing or breaking down URL
+20.5k Golang : Daemonizing a simple web server process example
+11.1k Golang : Activate web camera and broadcast out base64 encoded images
+13.6k Chrome : ERR_INSECURE_RESPONSE and allow Chrome browser to load insecure content
+10.9k Golang : http.Get example
+7k Golang : Heap sort example
+5.2k Golang : How to stop user from directly running an executable file?
+10k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+4.3k Golang : Find change in a combination of coins example
+32k Golang : Read a text file and replace certain words