This question already has an answer here:
I wonder why the following didn't marshall to json successfully? I am trying to use a very simple example to learn json package.
package main
import (
"encoding/json"
"fmt"
)
type Message struct {
username string `json:"name"`
message string `json:"message"`
}
func main() {
var m = Message{
username: "hello",
message: "world",
}
js, _ := json.Marshal(m)
fmt.Println(m)
fmt.Println(string(js))
}
</div>
username
message
start with a lowercase letter, meaning they are unexported (think private), and so are not visible to the encoding/json
package. You need to export your fields, or implement the MarshalJSON() ([]byte, error)
method and do it yourself.