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
+5.3k Golang & Javascript : How to save cropped image to file on server
+29.6k Golang : bufio.NewReader.ReadLine to read file line by line
+12.8k Golang : Get current time
+32.4k Golang : Create x509 certificate, private and public keys
+10.9k Golang : Pagination with go-paginator configuration example
+9.2k Golang : How to tokenize source code with text/scanner package?
+13.6k Golang : Adding XML attributes to xml data or use attribute to differentiate a common tag name
+6.2k Golang : Validate credit card example
+4.9k Javascript : How to replace HTML inside <div>?
+9.5k Golang : How to unmarshal JSON inner/nested value and assign to specific struct?
+3.3k Golang : Converting individual Jawi alphabet to Rumi(Romanized) alphabet example
+11.2k Golang : Display list of countries and ISO codes