1

I'm perplexed. When I POST with the following body

{"lng":1.23, "lat":4.56,"utc":789}

This one returns {0,0,0} (incorrect)

func test(rw http.ResponseWriter, req *http.Request) {
  type data struct {
    lng float64
    lat float64
    utc int
  }
  decoder := json.NewDecoder(req.Body)
  var t data
  err := decoder.Decode(&t)
  if err != nil {
      panic("PANIC")
  }
  log.Println(t)
}

This one returns {1.23, 4.56, 789} (correct)

func test(rw http.ResponseWriter, req *http.Request) {
  type data struct {
    Lng float64
    Lat float64
    Utc int
  }
  decoder := json.NewDecoder(req.Body)
  var t data
  err := decoder.Decode(&t)
  if err != nil {
      panic("PANIC")
  }
  log.Println(t)
}

The only difference is that I'm using uppercase letters in my struct definition. Am I missing something? Is this a bug?

joshula
  • 535
  • 1
  • 5
  • 19
  • See related questions: [1](http://stackoverflow.com/questions/26327391/golang-json-marshalstruct-returns/26327436), [2](http://stackoverflow.com/questions/26050469/json-unmarshall-not-working-properly/26050501), [3](http://stackoverflow.com/questions/25595096/unmarshalling-json-golang-not-working/25595269). –  Oct 19 '14 at 02:54

1 Answers1

15

The JSON encoding package works with exported fields only. The decoder is otherwise case insensitive.

You can control the case when encoding using field tags as described in the package documentation.

The Go Language is case sensitive.

Charlie Tumahai
  • 113,709
  • 12
  • 249
  • 242