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
+28.9k Golang : JQuery AJAX post data to server and send data back to client example
+7.5k Swift : Convert (cast) String to Double
+11.1k CodeIgniter : Import Linkedin data
+11.2k Golang : Display a text file line by line with line number example
+7.2k Golang : Set horizontal, vertical scroll bars policies and disable interaction on Qt image
+6k PHP : Proper way to get UTF-8 character or string length
+10.2k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example
+17.5k Golang : Put UTF8 text on OpenCV video capture image frame
+10.1k Golang : Select region of interest with mouse click and crop from image
+23.6k Golang : Call function from another package
+22.6k Golang : Randomly pick an item from a slice/array example
+35.3k Golang : Get file last modified date and time