Custom Search

Sunday, August 21, 2016

Go Golang json.Marshal returns {} when struct field start with lowercase

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 struc.
 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, _ := json.Marshal(p1)
fmt.Println("===p1_json===", string(p1_json))

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

/*With type and field name*/
/* %#v a Go-syntax representation of the value*/
fmt.Printf("=======%#v \n", p1)

}

1 comment: