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
+8.3k Swift : Convert (cast) Character to Integer?
+4.1k Detect if Google Analytics and Developer Media are loaded properly or not
+8.9k Android Studio : Image button and button example
+14.1k Golang : concatenate(combine) strings
+19.9k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+5.5k Golang : What is StructTag and how to get StructTag's value?
+8.6k Linux/Unix : fatal: the Postfix mail system is already running
+16.7k Golang : Generate QR codes for Google Authenticator App and fix "Cannot interpret QR code" error
+4.9k Javascript : How to get width and height of a div?
+23.6k Golang : Get ASCII code from a key press(cross-platform) example
+6.9k Swift : substringWithRange() function example
+7.5k Golang : Hue, Saturation and Value(HSV) with OpenCV example