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
+4.3k Golang : Valued expressions and functions example
+17.6k Golang : [json: cannot unmarshal object into Go value of type]
+16.7k Golang : read gzipped http response
+8.1k Android Studio : Rating bar example
+36.3k Golang : Convert date or time stamp from string to time.Time type
+15.6k Golang : Get checkbox or extract multipart form data value example
+10.5k Golang : ISO8601 Duration Parser example
+12.2k Golang : Get month name from date example
+23.9k Golang : Upload to S3 with official aws-sdk-go package
+15.5k Golang : rune literal not terminated error
+8.2k Golang : Configure Apache and NGINX to access your Go service example
+11.8k Golang : Convert(cast) bigint to string