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))
}

3 comments:

  1. In Go, you can pretty-print structs, maps, slices, and arrays using json.MarshalIndent, which formats JSON output with indentation for better readability. This is especially useful when working with complex data structures like those in Flipper Zero Unleashed for clear visualization and debugging.

    ReplyDelete
  2. Very informative and well-explained tutorial.The Golang-tutorial concepts are easy to understand, and the examples are helpful for beginners.Great learning resource Learn Golang-tutorial.

    ReplyDelete