Skip to content

How to Pretty Print JSON in Golang (Marshal Indent)

You need a simple way to format the output of your marshaled JSON output! Yes, Golang made it easy for us by using MarshalIndent function from JSON package:

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

Simple code example:

package main

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

type Response struct {
	Code int
	Data Data
}

type Data struct {
	Urls  []string
	Count int
}

func main() {
	res := Response{
		Code: http.StatusOK,
		Data: Data{
			Urls: []string{
				"https://www.code-paste.com/",
				"https://www.code-paste.com/category/golang/",
			},
			Count: 2,
		},
	}

	resBytes, err := json.MarshalIndent(res, "", " ")
	if err != nil {
		log.Fatal(err)
	}

	fmt.Println(string(resBytes))
}

1 thought on “How to Pretty Print JSON in Golang (Marshal Indent)”

  1. Pingback: Print Struct as String in Golang – Code Paste

Leave a Reply

Your email address will not be published. Required fields are marked *