Skip to main content
Back to Blog

How to Format JSON in Go (Golang)

Feb 03, 2026 3 min read

In Go, formatting JSON is done using the standard encoding/json package. You can use the json.MarshalIndent() function to easily pretty-print structs and maps into readable JSON strings.

Example Code

Go
package main

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

type User struct {
    Name   string   `json:"name"`
    Age    int      `json:"age"`
    City   string   `json:"city"`
    Skills []string `json:"skills"`
}

func main() {
    user := User{
        Name:   "John",
        Age:    30,
        City:   "New York",
        Skills: []string{"Go", "Microservices"},
    }

    // MarshalIndent takes a prefix and an indent string
    formattedJson, err := json.MarshalIndent(user, "", "  ")
    if err != nil {
        log.Fatalf("JSON marshaling failed: %s", err)
    }

    fmt.Println(string(formattedJson))
}

Common Use Cases

  • Dumping structs for debugging and logging
  • Generating indented configuration files
  • Streaming formatted JSON responses from a Go web server

💡 Pro Tips for Go

  • The first string argument in MarshalIndent is the prefix (usually empty ""), and the second is the indent (e.g. " " or "\t").
  • If you only have a raw JSON byte slice, you can use json.Indent(dst *bytes.Buffer, src []byte, prefix, indent string) to format it natively.

Speed Up Your Workflow

Don't waste time writing boilerplate. Use our free online formatter to beautify or minify your Go-generated JSON instantly.