-2

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))
}
ryan
  • 974
  • 2
  • 7
  • 13

1 Answers1

1
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.

dave
  • 62,300
  • 5
  • 72
  • 93