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
+6.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+17.8k Golang : Read data from config file and assign to variables
+14.3k Golang : Fix image: unknown format error
+10k Golang : Function wrapper that takes arguments and return result example
+5.5k Python : Delay with time.sleep() function example
+13.3k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+11.1k Golang : Create S3 bucket with official aws-sdk-go package
+8.6k PHP : How to parse ElasticSearch JSON ?
+6.2k Golang : Debug with Godebug
+20k Golang : How to get time from unix nano example
+34.8k Golang : How to stream file to client(browser) or write to http.ResponseWriter?