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
+17.6k Golang : How to make a file read only and set it to writable again?
+6.6k Golang : Join lines with certain suffix symbol example
+19.1k Golang : Get RGBA values of each image pixel
+12.5k Android Studio : Highlight ImageButton when pressed on example
+7.4k Golang : How to stop user from directly running an executable file?
+22.5k Golang : Set and Get HTTP request headers example
+5.9k Linux/MacOSX : Search for files by filename and extension with find command
+21k Golang : Clean up null characters from input data
+14.1k Golang : Get uploaded file name or access uploaded files
+4.9k Golang : Constant and variable names in native language
+7.1k Golang : Check if one string(rune) is permutation of another string(rune)