Source From Here
Question
I am trying to convert a Go struct to JSON using the json package but all I get is {}. I am certain it is something totally obvious but I don't see it.
HowTo
You need to export the User.name field so that the json package can see it. Rename the name field to Name:
Output:
I am trying to convert a Go struct to JSON using the json package but all I get is {}. I am certain it is something totally obvious but I don't see it.
- package main
- import (
- "fmt"
- "encoding/json"
- )
- type User struct {
- name string
- }
- func main() {
- user := &User{name:"Frank"}
- b, err := json.Marshal(user)
- if err != nil {
- fmt.Printf("Error: %s", err)
- return;
- }
- fmt.Println(string(b))
- }
You need to export the User.name field so that the json package can see it. Rename the name field to Name:
- package main
- import (
- "fmt"
- "encoding/json"
- )
- type User struct {
- Name string
- }
- func main() {
- user := &User{Name: "Frank"}
- b, err := json.Marshal(user)
- if err != nil {
- fmt.Println(err)
- return
- }
- fmt.Println(string(b))
- }
沒有留言:
張貼留言