0
0
GoHow-ToBeginner · 3 min read

How to Pretty Print JSON in Go: Simple Guide

To pretty print JSON in Go, use the json.MarshalIndent function from the encoding/json package. It formats JSON with indentation and line breaks for easy reading.
📐

Syntax

The json.MarshalIndent function takes four parameters: the data to encode, a prefix string for each line, an indent string for each indentation level, and returns the formatted JSON bytes and an error.

Its signature is:

func MarshalIndent(v interface{}, prefix, indent string) ([]byte, error)

- v: the data to convert to JSON.
- prefix: string added at the start of each line (usually empty).
- indent: string used for indentation (e.g., " " for two spaces).

go
json.MarshalIndent(v interface{}, prefix string, indent string) ([]byte, error)
💻

Example

This example shows how to pretty print a Go map as JSON with indentation of two spaces.

go
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	data := map[string]interface{}{
		"name": "Alice",
		"age": 30,
		"languages": []string{"Go", "Python", "JavaScript"},
	}

	prettyJSON, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		fmt.Println("Error marshalling JSON:", err)
		return
	}

	fmt.Println(string(prettyJSON))
}
Output
{ "age": 30, "languages": [ "Go", "Python", "JavaScript" ], "name": "Alice" }
⚠️

Common Pitfalls

One common mistake is using json.Marshal instead of json.MarshalIndent, which produces compact JSON without line breaks or indentation.

Another pitfall is ignoring the error returned by json.MarshalIndent, which can cause silent failures.

go
package main

import (
	"encoding/json"
	"fmt"
)

func main() {
	data := map[string]string{"hello": "world"}

	// Wrong: compact JSON
	compactJSON, _ := json.Marshal(data)
	fmt.Println(string(compactJSON))

	// Right: pretty print JSON
	prettyJSON, err := json.MarshalIndent(data, "", "  ")
	if err != nil {
		fmt.Println("Error:", err)
		return
	}
	fmt.Println(string(prettyJSON))
}
Output
{"hello":"world"} { "hello": "world" }
📊

Quick Reference

  • json.Marshal: Produces compact JSON without spaces or new lines.
  • json.MarshalIndent: Produces human-readable JSON with indentation.
  • Use empty string "" for prefix unless you want a line prefix.
  • Use spaces or tabs for indent string, e.g., " " for two spaces.
  • Always check the error returned by json.MarshalIndent.

Key Takeaways

Use json.MarshalIndent to pretty print JSON with indentation in Go.
Pass empty string for prefix and spaces for indent to format output nicely.
Always handle errors returned by json.MarshalIndent to avoid silent failures.
json.Marshal produces compact JSON without formatting, not suitable for pretty print.
Pretty printed JSON is easier to read and debug during development.