How to Pretty-Print Json in Go

Created
Modified

Using json.MarshalIndent Function

MarshalIndent is like Marshal but applies Indent to format the output. Each JSON element in the output will begin on a new line beginning with prefix followed by one or more copies of indent according to the indentation nesting.

package main

import (
  "encoding/json"
  "fmt"
)

func main() {
  str := `{"name":"Boo", "age":10}`

  // parses the JSON-encoded data
  var v map[string]interface{}
  json.Unmarshal([]byte(str), &v)

  b, err := json.MarshalIndent(v, "", "  ")
  if err != nil {
    // panic()
  }
  fmt.Println(string(b))
}
{
  "age": 10,
  "name": "Boo"
}

Using json.Indent Function

Indent appends to dst an indented form of the JSON-encoded src. You can use json.Indent function, it really simple. For example,

package main

import (
  "bytes"
  "encoding/json"
  "fmt"
)

func main() {
  str := `{"name":"Boo", "age":10}`

  var out bytes.Buffer

  err := json.Indent(&out, []byte(str), "", "  ")
  if err != nil {
    // panic()
  }
  fmt.Println(string(out.Bytes()))
}
{
  "name": "Boo",
  "age": 10
}

Related Tags

#pretty# #json#