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
+3.6k Swift : Convert (cast) Float to Int or Int32 value
+8.1k Golang : Edge detection with Sobel method
+21.2k Find and replace a character in a string in Go
+8.7k Generate Random number with math/rand in Go
+13k Golang : Loop each day of the current month example
+39k Golang : How to check if a string contains another sub-string?
+5.4k Golang : Array mapping with Interface
+4.8k Grep : How to grep for strings inside binary data
+10.7k Golang : Increment string example
+17.5k nginx: [emerg] unknown directive "passenger_enabled"
+4.3k Linux/MacOSX : Search for files by filename and extension with find command