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.2k Golang : Scan forex opportunities by Bollinger bands
+22.2k Golang : Print out struct values in string format
+14.6k Golang : How to reverse elements order in map ?
+12.3k Golang : Verify token from Google Authenticator App
+6.6k SSL : How to check if current certificate is sha1 or sha2 from command line
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+9.2k Golang : How to profile or log time spend on execution?
+17.1k Golang : Implement getters and setters
+10.6k Golang : Convert decimal number(integer) to IPv4 address
+12.5k Golang : Reverse IP address for reverse DNS lookup example
+8.7k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+4.9k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag