3 Easy Ways to Pretty Print JSON in Golang

Printing pretty JSON makes it easier to read and understand, especially when working with large or complex JSON data. In this article, we will see how to print JSON in Go pretty.

Golang pretty print json

There are 3 easy ways to pretty print json in Golang.

  1. json.MarshalIndent()
  2. json.Indent()
  3. Encoder.SetIndent()

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.

json.MarshalIndent(sample_data, "", " ")

The sample_data is a json object.

We can Marshal the JSON data to a byte string using the json.MarshalIndent() function.

Code 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.

The json.Indent() function accepts the JSON data as a string, a prefix string, and an indentation string and returns the indented JSON data as a string.

Code 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"
 }
]

In this program, we defined a new type called Company, which has three fields:

  1. Name (a string)
  2. Number (an int) 
  3.  Unit (a string)

In the next step, we created a slice of Company objects and initialized it with two elements.

Then we call the json.Marshal() function from json package converts the company slice into a JSON byte slice.

If there is an error during this process, it will be logged, and the program will exit.

Then, we created new bytes.

Finally, the buffer object is called out and initialized with an empty slice of bytes.

Then, we used to call the json.Indent() function to add indentation to the JSON data contained in the bt byte slice.

The out buffer should be used to store the indented JSON data, and each level of the data should be indented with a single space.

We used the WriteTo() method to write the contents of the out buffer to the standard output stream. And printed the pretty json in the console.

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.

Conclusion

To pretty print json in Golang, use the json.MarshalIndent() function. It is the easiest and most efficient way to do it.

Leave a Comment