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
+14.8k Golang : How to check if input from os.Args is integer?
+5.7k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+15.5k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file
+12.8k Golang : How to check if your program is running in a terminal
+6.9k Golang : Load DSA public key from file example
+12.2k Golang : reCAPTCHA example
+11.3k Golang : Remove or trim extra comma from CSV
+5.6k Golang : How to setup a disk space used monitoring service with Telegram bot
+10k Golang : How to use if, eq and print properly in html template
+5.4k Golang : Break string into a slice of characters example
+4k Fix Google Analytics Redundant Hostnames problem
+21.6k Golang : Strings to lowercase and uppercase example