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
+7.4k Golang : Check if one string(rune) is permutation of another string(rune)
+12.8k Golang : Pass database connection to function called from another package and HTTP Handler
+7.8k Golang : How to execute code at certain day, hour and minute?
+6.3k Golang : Grab news article text and use NLP to get each paragraph's sentences
+9.8k Golang : Eroding and dilating image with OpenCV example
+6k Cash Flow : 50 days to pay your credit card debt
+7.6k Golang : Create zip/ePub file without compression(use Store algorithm)
+33.9k Golang : convert(cast) bytes to string
+6.9k Golang : Calculate pivot points for a cross
+6.8k Golang : When to use make or new?
+23.3k Golang : Print out struct values in string format
+6.2k Golang : Debug with Godebug