There are three ways to pretty print json in Go.
- Using “json.MarshalIndent()” function
- Using “json.Indent()” function
- Using “Encoder.SetIndent()” function
Method 1: Using json.MarshalIndent()
The easiest way to pretty print json in Golang is to use the “json.MarshalIndent()” method. The json.MarshalIndent() function takes in the interface we want to marshal as well as the prefix string and the indent string.
Example
package main
import (
"encoding/json"
"fmt"
)
func main() {
sample_data := map[string]interface{}{
"car": "Lamborghini",
"company": "Volkswagen",
"specs": map[string]string{
"Fuel Type": "Petrol",
"Transmission Type": "Automatic",
},
}
formatted_data, err := json.MarshalIndent(sample_data, "", " ")
if err != nil {
fmt.Println(err)
return
}
fmt.Println(string(formatted_data))
}
Output
{
"car": "Lamborghini",
"company": "Volkswagen",
"specs": {
"Fuel Type": "Petrol",
"Transmission Type": "Automatic"
}
}
The json.MarshalIndent() function accepts the JSON data(sample_data) as a byte slice and an optional prefix(“”) and indentation string(” “) and returns the indented JSON data as a byte slice.
Method 2: Using json.Indent()
The json.Indent() function is from a package json/encoding that beautifies the JSON string without indentation to JSON with indentation.
Example
package main
import (
"bytes"
"encoding/json"
"log"
"os"
)
func main() {
type Company struct {
Name string
Number int
Unit string
}
company := []Company{
{"Lamborghini", 1, "million"},
{"Buggati", 3, "million"},
}
bt, err := json.Marshal(company)
if err != nil {
log.Fatal(err)
}
var out bytes.Buffer
json.Indent(&out, bt, "", " ")
out.WriteTo(os.Stdout)
println("\n")
}
Output
[
{
"Name": "Lamborghini",
"Number": 1,
"Unit": "million"
},
{
"Name": "Buggati",
"Number": 3,
"Unit": "million"
}
]
Method 3: Using Encoder.SetIndent()
The SetIndent() function instructs the encoder to format each subsequent encoded value as if indented by the package-level function. Using the json.Encode() function, you can set indentation through Encoder.SetIndent() method is similar to marshaling by defining a prefix and indent.
Example
package main
import (
"bytes"
"encoding/json"
"fmt"
"log"
)
func PrettyString(str string) (string, error) {
var prettyJSON bytes.Buffer
if err := json.Indent(&prettyJSON, []byte(str), "", " "); err != nil {
return "", err
}
return prettyJSON.String(), nil
}
func main() {
animalJSON := `{"type": "Cat", "name": "Fluffy", "age": 5}`
res, err := PrettyString(animalJSON)
if err != nil {
log.Fatal(err)
}
fmt.Println(res)
}
Output
{
"type": "Cat",
"name": "Fluffy",
"age": 5
}
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.