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))
}
Then when I try to run it I get this:
$ 6g test.go && 6l -o test test.6 && ./test
{}
Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:
The empty values are false, 0, any nil pointer or interface value, and
any array, slice, map, or string of length zero. The object's default
key string is the struct field name but can be specified in the struct
field's tag value. The "json" key in the struct field's tag value is the
key name, followed by an optional comma and options.
Related issue:
I was having trouble converting struct to JSON, sending it as response from Golang, then, later catch the same in JavaScript via Ajax.
Wasted a lot of time, so posting solution here.
In Go:
In JavaScript:
Hope this helps someone.
Best of luck.
You need to export the
User.name
field so that thejson
package can see it. Rename thename
field toName
.Output: