Golang : Clean formatting/indenting or pretty print JSON result

Tags : golang json indent clean-format


Your Golang program is producing JSON result in a single line that looks like this :


but you want to make the result human readable/clean formatted/indented or pretty print. How to do that?


Instead of using json.Marshal() function, use json.MarshalIndent() function instead.


 package main

 import (

 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))



Slice : [apple orange durian pear]

nicely indented/formatted JSON :







non-indented JSON :


Tags : golang json indent clean-format

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.