Golang encoding/json.MarshalIndent() function example

package encoding/json

MarshalIndent is like Marshal but applies Indent to format the output.

Golang encoding/json.MarshalIndent() function usage example

 package main

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

 type Employee struct {
 Name string
 Age  int
 Job  string
 }

 func main() {

 worker := Employee{
 Name: "Adam",
 Age:  36,
 Job:  "CEO",
 }

 output, err := json.MarshalIndent(worker, "%%%%", "$$") // <--- here

 if err != nil {
 fmt.Println(err)
 os.Exit(1)
 }

 fmt.Println(string(output))
 }

Output :

{

%%%%$$"Name": "Adam",

%%%%$$"Age": 36,

%%%%$$"Job": "CEO"

%%%%}

Reference :

http://golang.org/pkg/encoding/json/#MarshalIndent

Advertisement