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
+27.9k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+8.6k Golang : Progress bar with ∎ character
+9.5k Facebook : Getting the friends list with PHP return JSON format
+18.9k Golang : Read input from console line
+9k Golang : Go as a script or running go with shebang/hashbang style
+46.2k Golang : Read tab delimited file with encoding/csv package
+11.5k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+9.9k Golang : Get current, epoch time and display by year, month and day
+24.1k Golang : Find biggest/largest number in array
+6.7k Golang : Reverse by word
+13.2k Golang : Skip blank/empty lines in CSV file and trim whitespaces example
+9.5k Golang : Extract or copy items from map based on value