Custom Search

Sunday, August 21, 2016

Go Golang Pretty Print struct, map, slice, array json.MarshalIndent

package main

/* https://golang.org/pkg/fmt/ */
import (
"encoding/json"
"fmt"
)

/*A struct is a type which contains named fields.
Define new type named 'Person'*/
type Person struct {
Name    string
Age     int
Hobbies []string
}



func main() {

/*initialize a struct.
 Create an instance of type 'Person'*/
p1 := &Person{"Sam", 20, []string{"cricket", "football"}}
/*p1 := &Person{name: "Sam", age: 20, hobbies: []string{"cricket", "football"}}*/

p1_json_ind, _ := json.MarshalIndent(p1, "", "  ")
fmt.Println("==p1_json_ind==", string(p1_json_ind))

/*MAP*/
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.MarshalIndent(mapD, "", " ")
fmt.Println("==mapD==", string(mapB))

/*SLICE*/
/*https://blog.golang.org/go-slices-usage-and-internals
 https://blog.golang.org/slices*/
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.MarshalIndent(slcD, "", " ")
fmt.Println("==slice==", string(slcB))
}

1 comment: