Go - JSON pretty print example

In this source code example, we show how to JSON pretty print in Golang.

JSON (JavaScript Object Notation) is a lightweight data interchange format.

In Golang, the encoding/json package implements the encoding and decoding of JSON.

Check out Go - Convert an array/slice into a JSON

Go - JSON pretty print example

The output can be pretty printed with the MarshalIndent function.


package main

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

type Employee struct {
    Id         int
    FirstName       string
    LastName string
	Email string
}

func main() {

    employees := []Employee{
        {Id: 2, FirstName: "Amir", LastName: "Khan", Email: "Amir@gmail.com"},
        {Id: 3, FirstName: "Lucy", LastName: "Smith", Email: "Smith@gmail.com"},
        {Id: 4, FirstName: "David", LastName: "Brown", Email: "David@gmail.com"},
    }

    json_data2, err := json.MarshalIndent(employees, "", "	")

    if err != nil {

        log.Fatal(err)
    }

    fmt.Println(string(json_data2))
}

Output:

[
	{
		"Id": 2,
		"FirstName": "Amir",
		"LastName": "Khan",
		"Email": "Amir@gmail.com"
	},
	{
		"Id": 3,
		"FirstName": "Lucy",
		"LastName": "Smith",
		"Email": "Smith@gmail.com"
	},
	{
		"Id": 4,
		"FirstName": "David",
		"LastName": "Brown",
		"Email": "David@gmail.com"
	}
]


Comments